3

Is it possible to do something like we do in normal mysqli queries in prepared statements in while lopping. For example

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

In prepared statements, it goes like this

$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;
}

What i mean is i want to do the echo like so

echo $row['something'];

The solution i came up with now is to fetch them using bind result, then put them into an array inside the loop and then foo['bar']; or something of that sort. Is there a better way?

Manse
  • 37,765
  • 10
  • 83
  • 108
Marshall Mathews
  • 347
  • 5
  • 18

2 Answers2

3

Doesn't this work?

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

}
Dharman
  • 30,962
  • 25
  • 85
  • 135
ab_dev86
  • 1,952
  • 16
  • 21
1

You're almost there with your code. You just need to assign the value to $row within the while loop's condition check:

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

The data is now bound to the $item_poster_fetched variable from what I understand...

while($fetch_comments->fetch())
{
    $item_poster_fetched['something'];
}
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • thanks i was a bit confused as the while loop example in the manual was a tad bit different – Marshall Mathews Mar 20 '12 at 09:43
  • @cillosis `mysqli_stmt::fetch` returns a boolean, please read the question again. – xdazz Mar 20 '12 at 09:45
  • 1
    @xdazz Thanks for pointing that out, I was unaware of that behavior. I guess I've gotten too used to PDO. – Jeremy Harris Mar 20 '12 at 09:49
  • @cillosis i dont think thats how it works, because with bind_result, im binding a variable to one field. example: item_poster is binded to $item_poster_fetched and comment is binded to $comment_fetched – Marshall Mathews Mar 20 '12 at 10:02