Reputation: 325
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
}
}
Upvotes: 0
Views: 101
Reputation: 33531
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
}
}
Upvotes: 3
Reputation: 7597
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
.
Upvotes: 1
Reputation: 360752
$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.
Upvotes: 2