1

EDIT. My error ONLY occurs when calling database connection as a function, if I call my database connection normally, the error do not occur.

I'm trying to execute a prepare statement with database connection as a function so that it can be reused inside other functions. Executing normal SQL codes work when using database connection function but I'm getting errors when I try to use in a prepare statement.

This is my code.

function connect(){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";
    $conn = new mysqli($servername, $username, $password, $dbname);
    return $conn;
}

if (connect()->connect_error) {
    die("Connection failed: " . connect()->connect_error);
} else {
    echo "GOOD";
}

$val = "1";
$stmt = connect()->prepare("SELECT * FROM countries WHERE id = ?");
$stmt->bind_param("s",$val);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}
$stmt->close();

When connecting database as a normal variable such as this works.

$stmt = $conn->prepare("SELECT * FROM countries WHERE id = ?");

However, I get "Call to a member function fetch_assoc() on bool" whenever I tried to call my connection as a function. What am I doing wrong with this code?

Andy Brooke
  • 67
  • 1
  • 8
  • Possible duplicate of [Call to a member function fetch\_assoc() on boolean in ](https://stackoverflow.com/questions/35669088/call-to-a-member-function-fetch-assoc-on-boolean-in-path) – LLJ97 Sep 18 '19 at 11:15
  • @LLJ97 I only get the error when I call my connection as a function. When I call it the normal way, it works fine. – Andy Brooke Sep 18 '19 at 11:18

1 Answers1

0

After searching for a while and based on this answer, I was able fix my problem by declaring a variable for connection. However, this doesn't explain why directly calling connect doesn't work. Can somebody explain to me why the first way doesn't work?

$db = connect();
$stmt = $db->prepare("SELECT * FROM countries WHERE id = ?");
Andy Brooke
  • 67
  • 1
  • 8