views:

189

answers:

2

I've been requesting MySQL results and looping through them like this:

$query = "SELECT * FROM $table";
$result = mysql_query($query);
for($i = 0; $i < mysql_num_rows($result); $i++){
    echo mysql_result($result, $i, $row);
    //do something else;
}

you can probably see what happens. What if a row has been deleted? What if the first item is gone? In that case, there could be 30 items in the list, but the last items index is at position 50. How do I fix this or what other systems can I use?

+7  A: 
while($temp = mysql_fetch_assoc($result))
{
     echo $temp['id']; // ID Column
}

But BTW. The mysql_num_rows returns the number of rows you fetched. If you have a row that was deleted, it wouldn't have been fetched, and therefore it wouldn't count towards the number.

Chacha102
It should be noted that there are other functions besides mysql_fetch_assoc, the primary one being mysql_fetch_object, that works the same way except it returns an object of class stdClass. It can be used in a while() loop the same way mysql_fetch_assoc was here.
Steven Surowiec
+1  A: 

Also - I believe the entire rowset is obtained at query time, rows deleted after the query is executed will still appear in your results.

gnarf