
- PHP&MySQL 教程
- PHP&MySQL——主頁
- PHP&MySQL——概述
- PHP&MySQL——環境搭建
- PHP&MySQL 示例
- PHP&MySQL——連線資料庫
- PHP&MySQL——建立資料庫
- PHP&MySQL——刪除資料庫
- PHP&MySQL——選擇資料庫
- PHP&MySQL——建立表格
- PHP&MySQL——刪除表格
- PHP&MySQL——插入記錄
- PHP&MySQL——選擇記錄
- PHP&MySQL——更新記錄
- PHP&MySQL——刪除記錄
- PHP&MySQL——Where 子句
- PHP&MySQL——Like 子句
- PHP&MySQL——排序資料
- PHP&MySQL——使用聯合
- PHP&MySQL——處理 NULL
- PHP&MySQL——資料庫資訊
- PHP&MySQL 實用資源
- PHP&MySQL——快速指南
- PHP&MySQL——實用資源
- PHP&MySQL——討論
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
廣告