简体   繁体   中英

PHP set variable value again for sql query not working

Hello my question is quite simple, yet I can not understand why it works like this.

When I have set the varialbe $query once and then set it again it does not work. Only when using an other name for the variable, for example $query2 it works.

WORKS :

$connect = mysql_connect("","","") or die(mysql_error());
mysql_select_db("");
$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
WHILE 1
$query2 = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
$result2 = mysql_query($query2);
while($row2 = mysql_fetch_row($result2))
{
WHILE 2
}
}

NOT WORKS :

$connect = mysql_connect("","","") or die(mysql_error());
mysql_select_db("");
$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
WHILE 1
$query = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
$result = mysql_query($query);
while($row2 = mysql_fetch_row($result))
{
WHILE 2
}
}

You are not only changing the $query variable, but also the $result . Which is in your while , screwing up the first result set. You just have to assign a new result set.

This will work:

$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
   WHILE 1
   $query = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
   $result2 = mysql_query($query);
   while($row2 = mysql_fetch_row($result2))
   {
      WHILE 2
   }
}

$result is a HANDLE representing the results of the query. Your second query is OVERWRITING the result of the first query, effectively killing the first query's results:

$result = mysql_query($query1);
while($row = mysql_fetch_row($result)) {
    $result = mysql_query(...);
    ^^^^^^^---- overwrite occurs here

You run query #1, start the loop, run query #2. That query's results replaces the result from the first query, and gets completely consumed by the inner while() loop. When the inner loop finishes and control goes back up to the outer loop, there's no more data in this new $result handle, so the outer loop terminates as well.

Its because you are using while in while, it means yours second while:

$result = mysql_query($query);
while($row2 = mysql_fetch_row($result))

will overwrite yours first $result .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM