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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.