I do a mySQL query to get some data and then (for the purpose of debugging) print it out. In this particular sample there are 5 rows of data and each room_id in the database table has a value. However the print-out only shows the room_id of the first row.
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$row_rooms = mysql_fetch_assoc($rooms);
$numrows = mysql_num_rows($rooms);
$i = 0;
while ($i < $numrows) {
$room_id=$row_rooms['room_id'][$i];
echo $i." - ".$room_id."<br><br>";
++$i;
}
0 - 2
1 -
2 -
3 -
4 -
Can someone explain what is happening
You are fetching multiple rows.
So, you need to loop over the result set instead of fetching just one time.
Corrected code:
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$i=0;
while($row_rooms = mysql_fetch_assoc($rooms)) {
$room_id=$row_rooms['room_id'];
echo $i." - ".$room_id."<br><br>";
++$i;
}
Note: Never use mysql_ , they are deprecated and will be removed in the upcoming versions. Use mysqli_ or PDO instead.
Try like this
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$i = 0;
while ($row_rooms = mysql_fetch_assoc($rooms)) {
$room_id=$row_rooms['room_id'];
echo $i." - ".$room_id."<br><br>";
$i++;
}
You are looping $i instead of looping the $row_rooms.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.