如何使用PHP从预准备语句中获取结果?

时间:2014-05-11 16:37:43

标签: php arrays mysqli prepared-statement parameterized

我能够从标准的SQLi查询中获得结果,但是当涉及到预处理语句时,我很好,直到从查询中获取结果。

作为背景,查询将产生多行。

$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'];  
} 

这会导致“致命错误:在while循环条件下调用未定义的方法mysqli_stmt :: fetch_assoc()”。但是我已经尝试过PHP手册中概述但未成功的内容。

几天来一直困扰着我,谢谢你。

1 个答案:

答案 0 :(得分:0)

这是更好的方法。

$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
}

修改

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