Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My code is as follows

while ($row = mysql_fetch_assoc($result)) {
    $active_bid_ids = array_unique($row);
    $item_id = $active_bid_ids['item_id'];
    echo $item_id;
    echo '<br />';
    $sql = "SELECT item_name FROM items_list WHERE id='$item_id'";
    $result = mysql_query($sql, $cn) or
        die(mysql_error($cn));
    $row = mysql_fetch_assoc($result);
    $item_name = $row['item_name'];
    echo $item_name;
}

and it seems like the query gets run only one time if I have the additional sql query in the middle whereas is I remove the line

$sql = "SELECT item_name FROM items_list WHERE id='$item_id'";

the while function runs as normal and returns many results.

share|improve this question
You made mistake somewhere. But it still is not a good idea to perform query in a loop. – zerkms Aug 15 '11 at 22:39

1 Answer

up vote 1 down vote accepted

You're reusing your $result variable and $row variable which is throwing off your loop.

try:

while ($row = mysql_fetch_assoc($result)) {
   $active_bid_ids = array_unique($row);
   $item_id = $active_bid_ids['item_id'];
   echo $item_id;
   echo '<br />';
   $sql = "SELECT item_name FROM items_list WHERE id='$item_id'";
   $innerresult = mysql_query($sql, $cn) or
      die(mysql_error($cn));
   $innerrow = mysql_fetch_assoc($innerresult);
   $item_name = $innerrow['item_name'];
   echo $item_name;
}
share|improve this answer
1  
Best practice tips: parameterize your queries to avoid potential security vulnerabilities, and accomplish what you want in this case with a JOIN like this: SELECT I.item_name, A.active_bids_ids FROM active_bids A INNER JOIN items_list I on A.item_id = I.id – Code Magician Aug 15 '11 at 22:48
thank you for pointing out best practices. I will definitely be checking that out and studying a bit more before I finalize my code. – Qlidnaque Aug 16 '11 at 0:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.