PHP - Multiple while($row = mysql_fetch_array($variable)) { } ERRORS

两盒软妹~` 提交于 2019-12-05 05:00:32

The problem is that the query returns a resource. This resource has it's own internal pointer (counter to remember which row to return). mysql_fetch_array will advance that internal pointer and return each row from the resource one at a time. once it is at the end (no more rows left), it returns false. so on the last loop, $row equals false which exits the while loop. The pointer is not reset though. So on the next while loop, you call mysql_fetch_array, the pointer is at the end and so it returns false which completely bypasses the second while loop. What you should do, is loop through the data once and store each row into an array. Then you can copy/loop over the array as much as you want and everything works as expected.

$data = array();
while ($row = mysql_fetch_array($myVariable)) {
    $data[] = $row;
}
//now $data has all the rows. a simple foreach will loop over the data.
foreach($data as $row){
    //do events
    print_r($row);
}

//and you can loop over data again and again.
foreach($data as $row){
    //do events
    print_r($row);
}

Before the second loop, try using mysql_data_seek():

mysql_data_seek($myVariable, 0);

The pointer in the recordset needs to be reset, otherwise it will still indicate that it's at the end.

It may be a better option, as ZiTAL points out, to store your records in an array and just iterate over the array.

If your loops are nested, and assuming $myVariable is the same for both loops, just copy it and then loop over a different copy each time.

$myVariable = mysql_result($query);
$myVariable2 = $myVariable;

while ($row = mysql_fetch_array($myVariable)) {
    while ($row = mysql_fetch_array($myVariable2)) {
...

Another +1 for "make it an array" though, much nicer to work with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!