[英]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. 我能够从标准SQLi查询中获取结果,但是,对于准备好的语句,我会精打细算,直到从查询中获取结果为止。
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. 这将在while循环条件下导致“致命错误:调用未定义的方法mysqli_stmt :: fetch_assoc()”。 However I have tried what was outlined in the PHP manual but have not succeeded. 但是,我尝试了PHP手册中概述的内容,但没有成功。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.