如何編寫使用 MySQL JOINS 結合兩個 MySQL 表的 PHP 指令碼?


我們可以使用 MySQL JOIN 語法,將 SQL 命令與 PHP 函式 - mysql_query() 結合,來連線兩個表。該函式用於執行 SQL 命令,之後可以使用另一個 PHP 函式 - mysql_fetch_array() 提取所有選定的資料。

為了說明這一點,我們提供了以下示例 -

示例

在此示例中,我們使用了包含以下資料的兩個 MySQL 表 -

mysql> SELECT * FROM tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran          |      20        |
| mahnaz          |      NULL      |
| Jen             |      NULL      |
| Gill            |      20        |
| John Poul       |       1        |
| Sanjay          |       1        |
+-----------------+----------------+
6 rows in set (0.01 sec)

mysql> SELECT * from tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      1      |   Learn PHP    |   John Poul     |   2007-05-24    |
|      2      | Learn MySQL    |   Abdul S       |   2007-05-24    |
|      3      | JAVA Tutorial  |   Sanjay        |   2007-05-06    |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.00 sec)

下文是一個 PHP 指令碼,它將連線兩個表,選擇表 tutorials_tbl 中的所有作者並從 tcount_tbl 中選取教程數。

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
   FROM tutorials_tbl a, tcount_tbl b
   WHERE a.tutorial_author = b.tutorial_author';

   mysql_select_db('TUTORIALS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Author:{$row['tutorial_author']} <br> ".
         "Count: {$row['tutorial_count']} <br> ".
         "Tutorial ID: {$row['tutorial_id']} <br> ".
         "--------------------------------<br>";
   }
   echo "Fetched data successfully
";    mysql_close($conn); ?>

更新於: 2020 年 6 月 22 日

5000+ 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.