PHP&MySQL——使用聯合示例



PHP 使用 mysqli query()mysql_query() 函式從 MySQL 表中獲取記錄,方法是使用聯合。此函式需要兩個引數,成功時返回 TRUE,失敗時返回 FALSE。

語法

$mysqli->query($sql,$resultmode)

序列號 引數及描述
1

$sql

必需 - 使用聯合從多張表獲取記錄的 SQL 查詢。

2

$resultmode

可選 - 根據所需行為,可以是常量 MYSQLI_USE_RESULT 或 MYSQLI_STORE_RESULT。預設情況下,使用 MYSQLI_STORE_RESULT。

首先使用以下指令碼在 MySQL 中建立一張表並插入兩條記錄。

create table tcount_tbl(
   tutorial_author VARCHAR(40) NOT NULL,
   tutorial_count int
);

insert into tcount_tbl values('Mahesh', 3);
insert into tcount_tbl values('Suresh', 1);

示例

嘗試以下示例,透過聯合從兩張表中獲取記錄。 -

將以下示例複製並貼上到 mysql_example.php 中 -

<html>
   <head>
      <title>Using joins on MySQL Tables</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
         
         $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';
         $result = $mysqli->query($sql);
           
         if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
               printf("Id: %s, Author: %s, Count: %d <br />", 
                  $row["tutorial_id"], 
                  $row["tutorial_author"], 
                  $row["tutorial_count"]);               
            }
         } else {
            printf('No record found.<br />');
         }
         mysqli_free_result($result);
         $mysqli->close();
      ?>
   </body>
</html>

輸出

訪問部署在 Apache Web 伺服器上的 mysql_example.php 並驗證輸出。

Connected successfully.
Id: 1, Author: Mahesh, Count: 3
Id: 2, Author: Mahesh, Count: 3
Id: 3, Author: Mahesh, Count: 3
Id: 5, Author: Suresh, Count: 1
廣告