准备语句 fetch_assoc PHP mysqli

5

我在使用预处理语句时遇到了列出评论的问题,有什么建议吗?

这是我的代码:

$fetchComments = $cnx -> prepare("SELECT comment FROM comments WHERE video_id=? LIMIT 1");
$fetchComments -> bind_param('s', $row['id']);
$fetchComments -> execute();
$fetchComments -> store_result();
$fetchComments -> bind_result($vid_comment);
if ($fetchComments -> num_rows > 0) {
    whike ($row = mysqli_fetch_assoc($vid_comment)){
    echo $row['comment'];
    }
}

$row['id'] 是从哪里来的? - Fabio
问题是什么? - deceze
1
while ($fetchComments ->fetch()) { echo $vid_comment - Fabio
是的,这是面向对象的,而且是正确的。我可以发布答案,这样你就可以接受它了吗? - Fabio
当然可以 - 请继续!再次感谢! - sixli
显示剩余5条评论
2个回答

8
由于某些未知(非常奇怪)的原因,您不能在mysqli_stmt对象上使用fetch_assoc。
您需要使用mysqli_get_result()先获取mysqli结果资源。
另外,请一定要命名变量一致。mysqli语句与您的注释无关,并不知道它们,也不包含它们。它只是一个mysqli语句对象。
$stmt->execute();
$res = $stmt->get_result(); // here you go
while ($row = mysqli_fetch_assoc($res)) {
    echo $row['comment'];
}

尽管您无法确定mysqli是否可用此功能。

如果有人在使用get_result()时遇到问题,请参考以下内容:
  1. 如果出现致命错误,请安装mysqlnd:https://dev59.com/questions/NGsy5IYBdhLWcg3wyw-i
  2. 如果没有结果,请删除"$stmt->store_result()"这一行(其余不变)。
- suz

0

您的脚本出现了错误。您正在使用 mysqli_fetch_assoc,而应该使用 fetch()。错误在这里

while ($row = mysqli_fetch_assoc($vid_comment)){

所以你应该使用这个代替

while ($fetchComments ->fetch()) {
   echo $vid_comment 
}

您可以在此处查阅文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接