0

I have a problem with my JSON respons. In my mysql database I have two tables: Users and Games. When I try to get all the games from 1 user, I get those games in my respons but * the amount of different users I have in my Users table. So if I want all the games from a user with id 8, and that are for example 3 games, I get those games but times the amount of unique users I have, let's say 9. So the query returns 27 games (9 * 3 same games). What is it that I'm doing wrong here.

 $pm_id = $_POST["pm_id"];
 $pm_pass = $_POST["pm_pass"];
 $pm_timestamp = $_POST["pm_timestamp"];

try {
     $dbconn = 'mysql:host=' . DBHOST . ';dbname=' . DBDATA;
     $db = new PDO($dbconn, DBUSER, DBPASS);
 } catch (PDOException $e) {
     echo 'Connection failed: ' . $e->getMessage();
 }

 $statement = $db->prepare('SELECT * FROM users WHERE user_id = :id AND password =      :pass');
 $statement->execute(array(':id' => $pm_id, ':pass' => $pm_pass));
 $statement->setFetchMode(PDO::FETCH_ASSOC);

 $row = $statement->fetch();
     if($row['timestamp'] == $pm_timestamp){
         #no sync necessary
         echo json_encode("no sync needed");
     }else{
         #start sync
         $games = array();
         $statement_getAllGames = $db->prepare('SELECT game.game_id, game.user_id,       game.name, game.buyin, game.result, game.startDate, game.endDate, game.location,      game.isTournament, game.participants, game.endposition, game.comment, game.blinds,      game.pause,
         game.visibility, users.timestamp FROM game, users WHERE game.user_id = :id AND    game.timestamp > :timestamp');
         $statement_getAllGames->execute(array(':id' => $pm_id, ':timestamp' =>   $pm_timestamp));

         while($row = $statement_getAllGames->fetch(PDO::FETCH_ASSOC)){
             $games[] = array('game'=>$row);
         }
         echo json_encode(array('games'=>$games));

 };

If it's helpful I can add the structure of my tables.

nostradamus
  • 53
  • 1
  • 3
  • 11

1 Answers1

1
FROM game, users

You are missing the join condition game.user_id = user.user_id. You could add this to your WHERE clause, or you could use the newer SQL-92 join syntax (see INNER JOIN ON vs WHERE clause):

FROM game INNER JOIN users ON game.user_id = user.user_id
Community
  • 1
  • 1
PleaseStand
  • 31,641
  • 6
  • 68
  • 95