Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query goes in endless loop

Tags:

loops

php

mysql

The following goes into an endless loop, meaning it just constantly shows the same record over and over and over again.

<?php
while ($rowr = mysql_fetch_assoc(mysql_query("SELECT * FROM table1")) {
    while($rowu = mysql_fetch_assoc(mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'"))){
        while($rowc = mysql_fetch_assoc(mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'"))){
    ?>
    <tr><td><?php echo $rowc['post']; ?></td><td><a href="other.php?id=<?php echo $rowu['id']; ?>"><?php echo $rowu['username']; ?></a></td><td><a href="this.php?p=d&i=<?php echo $rowr['id']; ?>"><font color="#FF0000">X</font></a></td></tr>
    <?php
        };
    };
};
?>

Why does that happen and how can I fix it?

like image 241
Deniz Zoeteman Avatar asked Dec 01 '25 01:12

Deniz Zoeteman


2 Answers

You are putting the mysql query in the while statement so every time it gets there it does the same query and shows the same first record, you are never advancing to the next record in the result set.

Personally I would combine all queries into one, but to show how you can solve your problem (the same applies to all loops):

$results = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while ($rowc = mysql_fetch_assoc($results))
{
  // do stuff
}
like image 97
jeroen Avatar answered Dec 02 '25 13:12

jeroen


Simply because the query gets executed again every time the loop condition is checked. That means you'll always get the same result unless something changes in the database in the meantime.

You need something like this:

<?php
$res1 = mysql_query("SELECT * FROM table1");
while ($rowr = mysql_fetch_assoc($res1)) {

    $res2 = mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'");
    while($rowu = mysql_fetch_assoc($res2)){

        $res3 = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
        while($rowc = mysql_fetch_assoc($res3)){
?>
    <tr><td><?php echo $rowc['post']; ?></td><td><a href="other.php?id=<?php echo $rowu['id']; ?>"><?php echo $rowu['username']; ?></a></td><td><a href="this.php?p=d&i=<?php echo $rowr['id']; ?>"><font color="#FF0000">X</font></a></td></tr>
<?php
        }
    }
}
?>

That's just to illustrate why it doesn't work. As others already noted, combining your queries into one using JOIN would be advisable.

Btw, you don't need a ; after a {} block.

like image 37
Czechnology Avatar answered Dec 02 '25 13:12

Czechnology



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!