您好我正在创建游戏奖杯系统,我还在学习pdo。我的数据库中有两个表
第一桌(游戏)结构是
id, title, thumb, bronze, silver, gold, platinum
第二桌(奖杯)结构是
id, title, game_id
(game_id)专栏分配给游戏的每个奖杯
我想列出以下游戏
游戏名称
从总计
获得奖杯 x查询我只使用获得奖杯的总数我不知道如何从奖杯表中检索游戏奖杯数据
这是我的查询代码
$stmt = $db->query('SELECT * FROM trophies ORDER BY id DESC');
$numcat = $stmt->rowCount();
if($numcat == 0)
{
echo "There's No Trophies To Show";
}
else
{
foreach($db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games GROUP BY id DESC") as $row)
{
echo "
<div class='game_row'>
<div class='thumb_box'><img src='../images/thumbs/$row[thumb]' width='87' height='48' alt='$row[title]' /></div>
<div class='info_box'>
<span class='game_name'><a href='trophies.php?action=edit&game_id=$row[id]'>$row[title]</a></span><br />
<span class='game_trophy'>0 Of $row[total] Trophies</span>
</div>
</div>";
}
}
我试图使用join,我确定我错过了什么
我的加入查询
foreach($db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC") as $row)
我得到的错误
警告:为同一行中的foreach()提供的参数无效
答案 0 :(得分:4)
你需要这样做:
$sqlres=$db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC");
while($row=$sqlres->fetch_assoc())
{
echo $row["thumb"];
}
在SQL中进行连接时,需要指定字段表:
SELECT g.thumb, g.title, g.id, SUM(t.bronze + t.silver + t.gold + platinum) AS total FROM games g JOIN trophies t ON g.id = t.game_id GROUP BY g.id DESC
答案 1 :(得分:2)
试试这个:
$rows = $db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC");
foreach($rows as $r){
echo $r->thumb //etc.
}
您的标题sql错误是因为您有两个具有相同字段名称的表。你必须在标准连接中指定重复的字段,如:games.title,trophies.bronze等等。(对所有人来说这是好的做法,但只有在具有相同字段的表上才需要。因此模糊字段错误 - 我知道.MySQL需要显示更好的错误。太糟糕的Oracle买了它们,并没有专注于它。
然后,在返回查询结果后尝试在sql查询上运行foreach循环,以便可以使用它来遍历结果行。
答案 2 :(得分:1)
可能是字段ID模糊更改您的查询
SELECT games.thumb, games.title, games.id, SUM(games.bronze + games.silver + games.gold + games.platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY games.id DESC"