使用PHP从多个数据库表中获取数据

时间:2013-05-22 14:54:47

标签: php mysql mysqli

我正在尝试查询五个表。我可以使用

查询其中一个表
$query = "SELECT * FROM Stats_player WHERE player='$user'";

但是,当我尝试使用

查询另一个表时
$query = "SELECT * FROM Stats_player, Stats_block WHERE player='$user'";

网站破了。这是我用来回显屏幕上数据的代码

<?php 
if ($result = $mysqli->query($query)) {
echo "<img src=\"https://minotar.net/avatar/{$user}/100\"><h1>{$user}</h1><br/>";
    while ($row = $result->fetch_assoc()) {
        //variables
        $play_time = $row['playtime']/3600;
        $play_time = round($play_time, 1);
        $xpgained = $row['xpgained'];
        $damagetaken = $row['damagetaken'];
        $toolsbroken = $row['toolsbroken'];
        $itemscrafted = $row['itemscrafted'];
        $itemseaten = $row['omnomnom'];
        $commandsused = $row['commandsdone'];
        $teleports = $row['teleports'];
        $itemspickedup = $row['itempickups'];
        $itemsdroped = $row['itemdrops'];
        $lastseen = date("F j, Y ", strtotime($row['lastjoin']));
        //end of variables
            echo "<p>Time on Server: {$play_time} HRS</p>";
            echo "<p>Last Seen: {$lastseen}";
            echo "<p>Commands Used: {$commandsused}";
            echo "<p>XP Gained: {$xpgained}"; 
            echo "<p>Blocks broken: {$row['blockID']}"; //this is data from the table Stats_block
        }
    $result->free();
} 
$mysqli->close();
?>

关于我如何做到这一点的任何想法?

Stats_player的表结构: |柜台|球员|游戏时间|

Stats_block是: |柜台|球员| blockID |

3 个答案:

答案 0 :(得分:0)

如果没有看到两个表的结构,这样的事情就可以起作用。

SELECT columnList
FROM Stats_player a
LEFT JOIN Stats_block b ON b.player = a.player
WHERE a.player = '$user'

答案 1 :(得分:0)

你有没有试过这样的事情:

SELECT 
table1.field1, table1.field2, table2.field1, table2.field2
FROM
table1, table2
WHERE 
table1.field1 = " " and table2.field1 = " ";

答案 2 :(得分:0)

$query = "SELECT * FROM Stats_player, Stats_block WHERE player='$user'"

这很可能是错的。你应该使用JOIN operator

在这里,你只是在做两张桌子的笛卡尔产品,这几乎不是你想要的。如果表有很多行,那可能会超出你的资源(内存等)。

这样的东西
$query = "SELECT * FROM Stats_player p, Stats_block b 
WHERE p.block_id = b.id AND p.player='$user'"

$query = "SELECT * FROM Stats_player p INNER JOIN Stats_block b ON p.block_id = b.id
WHERE p.player='$user'"

或者LEFT OUTER JOIN ......

确切的查询将取决于您的架构。