【问题标题】:While looping in mysqli prepared statement [duplicate]在mysqli准备好的语句中循环时[重复]
【发布时间】:2012-04-04 18:24:08
【问题描述】:

是否有可能在 while lopping 的准备好的语句中做一些像我们在普通 mysqli 查询中所做的事情。 例如

$sql = "SELECT * FROM users"*;
$query = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($query)){
   echo $row['username'];
   echo $row['name'];
}

在准备好的语句中,它是这样的

$fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments WHERE status_id = ? and item_poster = ?");
$fetch_comments->bind_param("is", $status__id, $item_poster);
$fetch_comments->execute();
$fetch_comments->store_result();
$fetch_comments->bind_result($item_poster_fetched, $comment_fetched);
while($fetch_comments->fetch(){
  echo $item_poster;
}

我的意思是我想做这样的回声

echo $row['something'];

我现在想出的解决方案是使用绑定结果获取它们,然后将它们放入循环内的数组中,然后将它们放入 foo['bar']; 或类似的东西中。 有没有更好的办法?

【问题讨论】:

    标签: php arrays while-loop mysqli prepared-statement


    【解决方案1】:

    这不行吗?

    $fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments       WHERE status_id = ? and item_poster = ?");
    $fetch_comments->bind_param("is", $status__id, $item_poster);
    $fetch_comments->execute();
    $result = $fetch_comments->get_result();
    while ($row = $result->fetch_assoc()) {
    
        echo $row['something'];
    
    }
    

    【讨论】:

    • 我要试试这个,我认为这种方式行不通,因为手册中的示例不同......
    • 我没有mysqlnd驱动,有没有其他解决办法?
    • 所以在这种情况下 $fetch_cmets->get_result();指令失败......所以可能你最初提出的解决方案足够好......
    【解决方案2】:

    你的代码就快完成了。您只需在 while 循环的条件检查中将值分配给 $row:

    while( $row = $fetch_comments->fetch() ) {
       echo $row['somefield'];
    }
    

    据我所知,数据现在绑定到 $item_poster_fetched 变量...

    while($fetch_comments->fetch())
    {
        $item_poster_fetched['something'];
    }
    

    【讨论】:

    • 谢谢我有点困惑,因为手册中的 while 循环示例有点不同
    • @cilosis mysqli_stmt::fetch 返回一个布尔值,请再次阅读问题。
    • @xdazz 感谢您指出这一点,我不知道这种行为。我想我已经太习惯 PDO 了。
    • @cilosis 我不认为它是这样工作的,因为使用 bind_result,我将一个变量绑定到一个字段。示例:item_poster 绑定到 $item_poster_fetched,comment 绑定到 $comment_fetched
    猜你喜欢
    • 2014-11-14
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多