I'm converting some code to use prepared statements as is suggested when using mysqli
. The problem comes when I try to close the connection ($con
). No matter what I try, I get an error if I first close the prepared statement ($sql
).
The error is:
Exception has occurred. Warning: AdminDb::test(): Couldn't fetch mysqli_stmt
My guess is that the $sql_>close()
is also closing the connection as all of $con
's properties turn to null after the statement close. But everywhere I look I see example code closing the statement, then closing the connection. I've tried closing both within the try
block, pre-declaring $con
and $sql
, etc, all to no avail.
If I skip the statement close, the connection close works fine.
Here is a test function demonstrating the problem.
public function test(): bool {
try {
$con = new mysqli(self::$serverName, self::$userName, self::$password, self::$dbName, self::$port);
if ($con->connect_errno) throw new DatabaseException("Database connection failed: ($con->connect_errno) $con->connect_error");
$sql = $con->prepare("
SELECT `Id`
FROM `provider`
WHERE `HeaderText` = ?");
$sql->bind_param('s', $headerText);
$sql->execute();
$sql->store_result();
$sql->free_result();
return TRUE;
} catch (\Throwable $e) {
throw $e;
} finally {
if (isset($sql)) $sql->close();
if (isset($con)) $con->close();
}
}