When using mysqli_stmt::fetch() in PHP, proper preparation is required to ensure smooth execution. Below are the essential steps to follow.
Use the prepare() method to prepare an SQL query, typically containing placeholders (?) to prevent SQL injection:
$stmt = $mysqli->prepare("SELECT name, email FROM users WHERE id = ?");
if (!$stmt) {
die("Preparation failed: " . $mysqli->error);
}
If the SQL query contains placeholders (?), you need to bind the user input to the statement using the bind_param() method:
$userId = 5;
$stmt->bind_param("i", $userId); // "i" indicates integer type
Execute the SQL statement using the execute() method:
if (!$stmt->execute()) {
die("Execution failed: " . $stmt->error);
}
Before calling fetch(), you must bind the columns of the result set to PHP variables using the bind_result() method:
$stmt->bind_result($name, $email);
Now, you can use fetch() to fetch a row of data, automatically filling the previously bound variables with the result:
while ($stmt->fetch()) {
echo "Name: $name, Email: $email<br>";
}
Finally, close the statement and the connection:
$stmt->close();
$mysqli->close();
The preparation steps before calling mysqli_stmt::fetch include: creating a connection, preparing the statement, binding input parameters, executing the statement, and binding result variables. Each step is crucial, and once all preparations are completed, fetch() will successfully return the results.
Related Tags:
mysqli_stmt