pulling sql data within a while loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinehead18
Forum Contributor
Posts: 329
Joined: Thu Jul 31, 2003 9:20 pm

pulling sql data within a while loop

Post by pinehead18 »

Goal here is to get the id's then pull the names of each of the id's from a different table. This works great until the result = db->query from within the while loop. When i apply that i only get 1 result, instead of 7 which is how many rows are really in the db.

Any input is appreciated.

Thanks,

Code: Select all

    $db = new MySQL(); 
    $result = $db->query("SELECT id FROM users WHERE user_id <> '$user_id'");
    
    while($row = $db->FetchArray($result)) {
     $id = $row['id'];

              
        $result =$db->query("SELECT * FROM chains WHERE id = '$id'");
          var_dump($chain_result);
        $row1 = $db->FetchArray($result);        
        $desc = $row1['description'];
        $name = $row1['name'];

        echo $id;
        echo "Name: " . $name . " <a href=\"#\" class=\"joinChain\">Join Chain</a>";
        echo "<form method=\"post\" action=\"\"><input type=\"hidden\" class=\"id\" value=\"". $id . "\">";
        echo "<br /> Description: " . $desc;
        echo "<br /><br />";
        
        } 
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: pulling sql data within a while loop

Post by AbraCadaver »

How about just joining in the query and getting it all at once? Not tested but it's the general idea:

Code: Select all

$result = $db->query("SELECT * FROM users, chains WHERE users.id = chains.id AND users.user_id <> '$user_id'");
Last edited by AbraCadaver on Tue Oct 12, 2010 11:03 am, edited 1 time in total.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: pulling sql data within a while loop

Post by Jonah Bron »

The $result variable you're creating inside is interfering with the $result from outside. Change it to something else, like $result2.
Post Reply