views:

45

answers:

2

I have a while loop of a mysql call but I also am trying to run another mysql query inside of the while loop but it is only doing it once. I can not figure it out.

Here is my code:

$sql = "SELECT * FROM widget_layout WHERE module_id=".mysql_real_escape_string($id)." AND state='".mysql_real_escape_string($page)."' AND position=".mysql_real_escape_string($position);

$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
    $layout .= $row['widget_id'].'<br/>'; //test if it is looping through all rows
    $sql2 = "SELECT title FROM widgets WHERE id=".$row['widget_id'];
    $query2 = mysql_query($sql2);
    $result2 = mysql_fetch_array($query2);
    $layout .= $result2[0]; // test the title output
}

It is looping through the first query no problem but the second query is only load the title of the first widget, return null for the rest. Any idea of why this is doing this?

+2  A: 

You don't have to use a WHILE loop -- this can be done in a single SQL statement:

SELECT wl.widget_id,
       w.title
  FROM WIDGET_LAYOUT wl
  JOIN WIDGETS w ON w.id = wl.widget_id
 WHERE wl.module_id = mysql_real_escape_string($id)
   AND wl.state = mysql_real_escape_string($page) 
   AND wl.position = mysql_real_escape_string($position);

The issue with NULL title values depends on if the WIDGET.title column is NULLable, or there isn't a record in the WIDGETS table for the id value. You need to check the values coming back from the first query, confirm they have supporting records in the WIDGETS table first, then look at the title value...

OMG Ponies
A: 

Directly from the mysql_query() docs: multiple queries are not supported. Your innery query is killing the outer one.

Marc B
You are wrong. The posted code have queries in sequence. Not multiples!
Keyne
You are wronger. $query2 is within a while() loop that is consuming results from the outer $query. As long as the other $query is in use, you cannot issue another query with the standard mysql_query without killing the previous one. They may be two separate query statements, but the mysql_* functions do NOT support multiple active queries at the same time on the same connection handle.
Marc B
Have you tested? I already tested and everything works fine. So you are missing something. I have many projects working with this approach. Multiple queries isn't what the questioner is doing. Is one query per call! Look here and see the difference: http://dev.mysql.com/doc/refman/5.1/en/c-api-multiple-queries.html
Keyne
Once mysql_query() is executed the result is stored on a specific resource (complete result set), then you loop through this resource and for each item you perform another mysql_query() which have a difference resource as result. There isn't an "outer query" working with an "inner query"!
Keyne