PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何编写PHP脚本,使用MySQL JOINS在其中连接两个MySQL表格?

王林
王林 转载
2023-08-20 11:57:16 388浏览

如何编写PHP脚本,使用MySQL JOINS在其中连接两个MySQL表格?

为了说明这一点,我们有以下示例−

示例

在这个示例中,我们使用了两个具有以下数据的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); ?>

以上就是如何编写PHP脚本,使用MySQL JOINS在其中连接两个MySQL表格?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除