简体   繁体   中英

How do I get a result from a prepared statement using PHP?

I am able to get the result from a standard SQLi query however when it comes to prepared statements I am fine up until it comes to getting the result from the query.

As background the query will result with more than one row.

$sql = "SELECT * FROM blog WHERE ID=?";

if (!$stmt = $con -> prepare($sql)) {
    echo "Prepare failed: (" . $con->errno . ") " . $con->error;
}

if (!$stmt->bind_param("i", $_GET["ID"])) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

while($row = $stmt->fetch_assoc()){
    $blog_title = $row['title'];
    $blog_body = $row['body'];
    $blog_blurb = $row['blurb'];
    $blog_date = $row['posted'];
    $blog_tags = $row['tags'];  
} 

This results in "Fatal error: Call to undefined method mysqli_stmt::fetch_assoc()" on the while loop condition. However I have tried what was outlined in the PHP manual but have not succeeded.

It's been bugging me for days, Thank you in advance.

Here is better way to do it.

$mydatabase = new mysqli('localhost', 'root', '', 'database');
if ($mydatabase->connect_errno) {
echo "Failed to connect to Database";
}

$id = $_GET['id'];
$stmt = $mydatabase->prepare("SELECT * FROM `blog` where ID = ?");
echo $mydatabase->error;//this will display error if something goes wrong.
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();//get the results

while($row = $result->fetch_assoc()){
echo $row['whatever'];//do whatever here
}

Edit

 $stmt->bind_result($column1, $column2);
while ($stmt->fetch())
{
 echo $column1;
echo $column2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM