在mysqli准备语句中使用fetch_array的SELECT语句

3

我经常发现编写MySQLi预处理语句很困难,因为许多函数的工作方式与旧版本不同。目前我面临一个关于fetch_array()的问题。

$stmt = $db->prepare("SELECT category_id FROM post_items Where user_id = ?");
$stmt->bind_param('i', $userid);
$result = $stmt->execute();
while ($row = $result->fetch_array()) {
    // ...
}
3个回答

15

你正在尝试通过

$result = $stmt->execute();

然而事实并非如此。因为execute仅会返回一个布尔值。

请按以下方式执行。

$stmt = $db->prepare("SELECT category_id FROM post_items Where user_id = ?");
$stmt->bind_param('i', $userid);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
        //result is in row
}

运行得很好,谢谢!所以我的错误是假设execute()返回结果是正确的?所以我需要使用get_result()。get_result()和query()一样吗? - user3277912
不要替换绑定结果步骤。否则,我猜你应该执行bind_result - Mithun Satheesh
get_result() 是做什么的?我用 $result = $db->query($query) 得到了相同的结果.. 为什么? - user3277912

0

$stmt->execute();不返回结果。你需要使用 $stmt->get_result();

你可以像这样重写代码:

$stmt = $db->prepare("SELECT category_id FROM post_items Where user_id = ?");
$stmt->bind_param('i', $userid);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
    // ...
}

-1

替换这个:

    $result = $stmt->execute();
    while ($row = $result->fetch_array()) {

通过这个

  $stmt->bind_result($category_id);

  while($stmt->fetch()){
       $myArray=$category_id;
  }

但是mithunsatheesh的方法有效,能否请您解释更多? - user3277912
两种方式都是正确的,我的方式是将stmt的结果绑定到一个变量上,然后获取stmt并使用你绑定的变量。 - CodeBird

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