我的JSON响应有问题。在我的mysql数据库中,我有两个表:用户和游戏。当我尝试从1个用户获得所有游戏时,我会在我的响应中获得这些游戏,但*我在Users表中拥有的不同用户数量。因此,如果我想要来自id为8的用户的所有游戏,例如3个游戏,我会得到那些游戏,但是我拥有的独特用户数量,让我们说9个。所以查询返回27个游戏(9 * 3)同样的游戏)。我在这里做错了什么。
$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));
};
如果它有用,我可以添加表格的结构。
答案 0 :(得分:1)
FROM game, users
您缺少加入条件game.user_id = user.user_id
。您可以将其添加到WHERE子句中,也可以使用较新的SQL-92连接语法(请参阅INNER JOIN ON vs WHERE clause):
FROM game INNER JOIN users ON game.user_id = user.user_id