Jump to content

re-using php queries


karldesign

Recommended Posts

I have the following code:

 

$sql_query = mysql_query("SELECT * FROM tbl_name");

while($arr = mysql_fetch_array($sql_query)){
// do something
}

// further down the page

while($arr = mysql_fetch_array($sql_query)){
// do something again
}

 

The first statement works correct, yet the second doesn't output. Why is this?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/118425-re-using-php-queries/
Share on other sites

First of all, if you are using the same result in two places, then get them into an array once, and use that array whenever needed.

As to ur problem, you maybe overwriting the $sql_query variable at some point be using it second time. Please post ur full code?...

 

Regards

Link to comment
https://forums.phpfreaks.com/topic/118425-re-using-php-queries/#findComment-609574
Share on other sites

You'll need to reset the row that your working on between the two loops with mysql_data_seek.

 

When you use the mysq_fetch_xxxx functions, it reads the current row of the result set into an array and advances the internal pointer. This means that next time you use the function, you work with the following row in the result set. At the end of the first loop, you've reached the end of the result set. So at the next while loop, you're already at the end of the result set. That's why you need to reset the pointer.

Link to comment
https://forums.phpfreaks.com/topic/118425-re-using-php-queries/#findComment-609620
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.