I am making a function to more easily use prepared statements in sql queries. But while working on it, I ran into a strange bug.
When you run the code below the first var_dump
of $response
prints the $stmt
variable like I expect it to, but after closing the $stmt
it give a lot of Warnings and prints a NULL filled version of $stmt
. I only make a copy of $stmt as $response
, so I wouldn't expect $response
to change when closing $stmt
.
Could someone explain why this happens and how I can prevent it?
function sql_bug() {
global $dbc; // Database connection
$sql = "UPDATE users SET username = 'J0R1AN' WHERE id = 1"; // Test query
if ($stmt = $dbc->prepare($sql)) {
if ($stmt->execute()) {
$response = $stmt->get_result();
if ($response === false) {
// Checks for e.g. UPDATE queries that return bool(false) instead of a mysqli_result,
// and sets $response to $stmt instead, to return more valuable information when using UPDATE
$response = $stmt;
}
var_dump($response); // Prints expected $stmt variable
$stmt->close(); // Somehow changes $response?
var_dump($response); // Prints $stmt variable filled with NULLS
return $response;
}
}
return false;
}