I was going through some tutorials on prepared statements, and I couldn't figure out how to loop through results that contain multiple rows. I am used to the procedural style of
while($row = mysqli_fetch_array($result))
However I cannot for the life of me figure out how to do this with the prepared statement format.
if($stmt = $mysqli->prepare("SELECT * FROM `Products` WHERE name LIKE '%?%'")){
$stmt->bind_param("s", $query); //query is $_GET['query'], user input
$stmt->execute();
$result = null;
$stmt->bind_result($result);
while($stmt->fetch()){ //problematic code...
echo $result;
}
$stmt->close();
}
How can I loop through multiple rows resulting from a prepared statement SQL query in PHP?
EDIT (new code as requested):
/* Create a prepared statement */
if($stmt = $mysqli->prepare("SELECT name, price, description, file FROM `Products` WHERE name LIKE '%?%'")){
$stmt->bind_param("s", $query) or die('bind_param');
$query = trim(htmlspecialchars($_GET['query']));
$stmt->execute() or die('execute');
$stmt->bind_result($name, $price, $description, $file) or die('bind_result');
while($stmt->fetch()){
echo $name;
}
$stmt->close();
}