mysql_fetch_array loop not working while result set contains rows
October 27, 2009
Last night I ran into the crazy problem that a mysql result set contained rows (confirmed with mysql_num_rows) but I wasn’t able to fetch the rows in mysql_fetch_array while loop construction. I managed to create a workaround but I posted a note on the php.net mysql_fetch_array page asking for an explanation. The note got rejected so I figured I could use my own blog in the search for an answer.
Here is the note;
I hope someone can help me with this question.
I have 2 code snippets. The first works, the second doesn’t. I would prefer using the second code snippet because it seems cleaner. What’s wrong with the second code snippet?
This works;
$results = mysql_query("SELECT DISTINCT(col) FROM table WHERE col!='' ORDER BY RAND()");
for( $i = 0; $i < mysql_num_rows( $results ); $i++ )
{
// do something with mysql_result($results,$i,0);
}
This doesn’t work;
$results = mysql_query("SELECT DISTINCT(col) FROM table WHERE col!='' ORDER BY RAND()");
while($result = mysql_fetch_array($results))
{
//do something with $result
}


November 17, 2009 at 3:38 pm
The second construct should work as well, i’ve never used anything else. What are you actually doing withing the body? Try inspecting the data that comes out of it using print_r($result)
November 18, 2009 at 7:06 am
Thanks for your comment Michiel,
Just like you I’ve never used anything else. But the query “SELECT DISTINCT(col) FROM table WHERE col!=” ORDER BY RAND()” does not work with the while loop.
I’ve tested your print_r($result) suggestion. The only thing that happens is that the loop repeatedly prints nothing. In my case it loops 6 times and 6 times prints nothing.
August 13, 2011 at 8:06 am
I also face this problem and after code review i got what is the actual problem, problem is in my database connectivity path.