简体   繁体   中英

Using PHP to get data from multiple database tables

I am trying to query five tables. I am able to query one of the tables with

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

However, when I try to query another table with

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

the website breaks. Here is the code I am using to echo the data on the screen

<?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();
?>

Any ideas on how I might do this?

Table structor of Stats_player: | counter | player | Playtime |

Stats_block is: | counter | player | blockID |

Without seeing the structure of both tables, something like this could work.

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

Have you tried something like this:

SELECT 
table1.field1, table1.field2, table2.field1, table2.field2
FROM
table1, table2
WHERE 
table1.field1 = " " and table2.field1 = " ";
$query = "SELECT * FROM Stats_player, Stats_block WHERE player='$user'"

That's very likely wrong. You should use a JOIN operator .

Here, you are just doing a cartesian products of the two tables, that's hardly what you want. And that may overrun your resource (memory etc.) if the tables have a lot of rows.

Something like

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

or

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

or maybe LEFT OUTER JOIN...

The exact query will depend on your schema.

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