同时在mysqli中循环准备语句

时间:2012-03-20 09:29:55

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

是否有可能像在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'];或类似的东西。 还有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

这不起作用吗?

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

}

答案 1 :(得分:1)

你的代码几乎就在那里。您只需要在while循环的条件检查中将值赋给$ row:

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

<击>

现在数据已根据我的理解绑定到$item_poster_fetched变量......

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