Page 1 of 1
mysql_query again and again
Posted: Tue Mar 02, 2010 9:14 am
by klevis miho
Why do I need to do a mysql_query again and again like this:
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
//do something
}
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
//do something
}
The second loop will not work if I dont put the $query before it.
Re: mysql_query again and again
Posted: Tue Mar 02, 2010 9:21 am
by davex
Hi,
I take it the query is the same both times and so you want to loop through?
The reason is because the first loop will read through all records and move the data pointer to the end.
If you just want to loop through the results again you can use mysql_data_seek($query,0) - this will reset the data pointer to the start.
However the method I would really suggest (unless maybe it's a lot of data) is to read it all into an array and then just loop through that twice.
Regards,
Dave.
Re: mysql_query again and again
Posted: Tue Mar 02, 2010 9:24 am
by klevis miho
Thnx Dave, it makes sense.
But what if I rename the second $row to $row1?
Re: mysql_query again and again
Posted: Tue Mar 02, 2010 9:36 am
by davex
Hi,
The name of the row doesn't matter...
Code: Select all
$result=mysql_query("SELECT * FROM table");
while ($row=mysql_fetch_array($result)) // every time fetch_array is called it returns a row and MOVES THE DATA POINTER ON
{
echo $row['field']."<BR />";
}
// at the end of the loop the data pointer is AT THE END OF THE DATA - another fetch_array will return FALSE
// however...
mysql_data_seek($result,0); // sets the data pointer back to the start (record 0)
while ($call_this_anything = mysql_fetch_array($result)) // will return the same records as the first while
{
echo $call_this_anything['field']."<BR />"; // same output
}
Hope that makes sense.
Cheers,
Dave.
Re: mysql_query again and again
Posted: Tue Mar 02, 2010 9:42 am
by rizjav_86
Renaming $row to $row1 will not help because mysql_fetch_array has already read the entire $query in the first loop.
so even if you change it to $row1 the mysql_fetch_array will start from the end of $query.
you need to "reset" your resultset by using the method suggested by davex.
Re: mysql_query again and again
Posted: Tue Mar 02, 2010 9:57 am
by klevis miho
Very thanks Dave, it make a lot more sense now

Re: mysql_query again and again
Posted: Tue Mar 02, 2010 1:24 pm
by davex
No problem - good luck with your project.
Regards,
Dave.