简体   繁体   中英

Query table and then query another table for each result and then … etc

I need to query a database where location = $location . This will return some user_id s.

I then need to query another database where user_id = those previous user_id results. This will find game_id s.

I then need to query another table with those game_id s to get the name of each game (each game name is assigned with an id.)

This what I have:

 if (isset($_POST['location'])) {
        $location = $_POST['location'];
        $query = mysql_query("SELECT * FROM users WHERE location = '$location'") or die(mysql_error());

        echo "<ul>";
        while ($row = mysql_fetch_array($query)) {
            foreach (explode(", ", $row['user_id']) as $users) {
                echo "<li>" . $row['user_name'] . "<ul><li>";
               //this where I need I need to query another table where user_Id = $user (each user found in previous query)
//this will find multiple game id's (as $game) , I then need to query another table to find game_id = $game
// output name of game
                echo "</li></ul></li>";
            }  
        }
        echo "</ul>";
      }

Sounds complicated. Is there a simpler way?

Such a query will produce the location, user_id, game_id table. Put as much effort in your SQL query so that you will be able to handle it easily by your code:

$query = mysql_query("SELECT game_name FROM another_table \
                      JOIN users \
                      JOIN games \
                      WHERE users.location = '$location'")
         or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
    echo $row['game_name']; //Here is the game name
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM