簡體   English   中英

用PHP連接兩個MySQL表

[英]Join two MySQL tables with PHP

例如,我創建了兩個頁面和兩個MySQL表。

Index.phpcitys.php

全市

 ID     City       Country  Population
 --------------------------------------
 1      Amsterdam     NL     1500000
 2      Rotterdam     NL     900000
 3      Dusseldorf    DE     1800000

評論

ID   City        Name   Comment
---------------------------------
 1   Dusseldorf  Jack   Great city!
 2   Dusseldorf  John   Beautiful
 3   Rotterdam   Emy    Love it

目前,我只使用這樣的表格citys

index.php鏈接到citys.php

<a href='citys.php?cmd=menu&id=";echo $row['id'];echo "'>

citys.php使用以下代碼顯示來自MySQL的數據:

<?php
    include "connect.php";
    if(!isset($cmd))
    {
        if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
        {
            if (!isset($_POST["submit"]))
            {
                $id = $_GET["id"];
                $sql = "SELECT * FROM citys WHERE id=$id";
                $result = mysql_query($sql);
                $row = mysql_fetch_array($result);
?>

<?php echo $row["City"] ?>
<br><br>

<?php echo $row["Country"] ?>
<br><br>
<?php echo $row["Population"] ?>

直到這里一切都顯示出來並且工作正常。

但我也想在第2頁上顯示注釋。因此,必須對查詢進行編輯以從表comments獲取正確的數據。

我嘗試了一些自己編輯過的互聯網示例,例如:

<?php
    include "connect.php";
    if(!isset($cmd))
    {
        if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
        {
            if (!isset($_POST["submit"]))
            {
                $id = $_GET["id"];
                $sql = "SELECT citys.*, comments.* FROM citys, comments WHERE citys.id=$id AND comments.city=citys.city";
                $result = mysql_query($sql);
                $row = mysql_fetch_array($result);
?>

但沒有任何作用。

我怎樣才能解決這個問題?


VIPIN JAIN的答案查詢有效,但是還存在一個問題:

查詢:

$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";

如果表“ comments”具有三行,則此代碼僅顯示最后兩行,而不顯示第一行:

<?php
    while($row = mysql_fetch_array($result)) {
        echo "<br><br>";
        echo $row['name'];
        echo "<br>";
        echo $row['comment'];
    }
?>

如果我嘗試這樣做,它只會顯示第一行。

<?php echo $row["name"] ?>
<br>
<?php echo $row["comment"] ?>

我不知道為什么第一條記錄沒有留在循環中。

使用此查詢

$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";

使用leftjoin進行此類工作

select * from citys 
left join comments on comments.city = citys.city 
where citys.id=$id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM