【问题标题】:SELECT statement with fetch_array in mysqli prepared statements在 mysqli 准备好的语句中使用 fetch_array 的 SELECT 语句
【发布时间】:2014-02-14 07:30:15
【问题描述】:

我总是发现很难编写 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()) {
    // ...
}

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    您正在尝试通过

    获取结果
    $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
    }
    

    【讨论】:

    • 工作就像一个魅力 thx!所以我的错误是假设 execute() 返回结果对吗?所以我需要使用 get_result()。 get_result() 和 query() 一样吗?
    • 不能替代绑定结果步骤。否则你应该做一个bind_result 我猜。
    • get_result() 是做什么的?我得到了 $result = $db->query($query).. 为什么返回相同的结果??
    【解决方案2】:

    $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) {
        // ...
    }
    

    【讨论】:

      【解决方案3】:

      替换这个:

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

      通过这个

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

      【讨论】:

      • 但是 mithunsatheesh 方法是有效的,请解释一下吗?
      • 两种方式都是正确的,我的方式是你将 stmt 的结果绑定到一个变量,然后获取 stmt 并使用你绑定到的变量。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2018-12-11
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多