當用PHP訪問數據庫時,除了PHP自帶的數據庫驅動,咱們通常還有兩種比較好的選擇:PDO和MySQLi。php
注意:自PHP5.5開始,傳統的mysql擴展已經廢棄,只能使用PHP提供的MySQLi擴展或PDO擴展html
PDO | MySQLi | |
---|---|---|
Database support | 12 different drivers | MySQL only |
API | OOP | OOP + procedural |
Connection | Easy | Easy |
Named parameters | Yes | No |
Object mapping | Yes | Yes |
Prepared statements (client side) | Yes | No |
Performance | Fast | Fast |
Stored procedures | Yes | Yes |
若是你的項目須要在多種數據庫中切換,建議使用 PDO;若選用MySQLi,在多種數據庫中切換時候,你須要從新編寫全部代碼。mysql
MySQLi專門針對MySQL設計的,因此MySQLi相對於PDO性能稍微好一些。sql
MySQLi - 面向對象的鏈接方法數據庫
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 建立鏈接 $conn = new mysqli($servername, $username, $password); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } echo "鏈接成功"; ?>
MySQLi - 面向過程的鏈接方法數組
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 建立鏈接 $conn = mysqli_connect($servername, $username, $password); // 檢測鏈接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "鏈接成功"; ?
PDO 的鏈接方法服務器
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); echo "鏈接成功"; } catch(PDOException $e) { echo $e->getMessage(); } ?>
鏈接在腳本執行完後會自動關閉。可使用如下代碼來關閉鏈接:併發
MySQLi - 面向對象的關閉鏈接方法app
$conn->close();
MySQLi - 面向過程的關閉鏈接方法ide
mysqli_close($conn);
PDO關閉鏈接的方法
$conn = null;
使用CREATE DATABASE語句建立數據庫
MySQLi - 使用面向對象的方式建立數據庫
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 建立鏈接 $conn = new mysqli($servername, $username, $password); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } // 建立數據庫 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "數據庫建立成功"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>
MySQLi-使用面向過程的方式建立數據庫
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 建立鏈接 $conn = mysqli_connect($servername, $username, $password); // 檢測鏈接 if (!$conn) { die("鏈接失敗: " . mysqli_connect_error()); } // 建立數據庫 $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "數據庫建立成功"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
PDO 建立數據庫
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // 設置 PDO 錯誤模式爲異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE myDBPDO"; // 使用 exec() ,由於沒有結果返回 $conn->exec($sql); echo "數據庫建立成功<br>"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
使用CREATE TABLE語句建立數據表
咱們將建立一個名爲 "MyGuests" 的表,有 5 個列: "id", "firstname", "lastname", "email" 和 "reg_date":
CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } // 使用 sql 建立數據表 $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "建立數據表錯誤: " . $conn->error; } $conn->close(); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 檢測鏈接 if (!$conn) { die("鏈接失敗: " . mysqli_connect_error()); } // 使用 sql 建立數據表 $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; if (mysqli_query($conn, $sql)) { echo "數據表 MyGuests 建立成功"; } else { echo "建立數據表錯誤: " . mysqli_error($conn); } mysqli_close($conn); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 設置 PDO 錯誤模式,用於拋出異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 使用 sql 建立數據表 $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; // 使用 exec() ,沒有結果返回 $conn->exec($sql); echo "數據表 MyGuests 建立成功"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 檢測鏈接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 設置 PDO 錯誤模式,用於拋出異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // 使用 exec() ,沒有結果返回 $conn->exec($sql); echo "新記錄插入成功"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢查連接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if ($conn->multi_query($sql) === TRUE) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立連接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 檢查連接 if (!$conn) { die("鏈接失敗: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "新記錄插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 開始事務 $conn->beginTransaction(); // SQL 語句 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"); // 提交事務 $conn->commit(); echo "新記錄插入成功"; } catch(PDOException $e) { // 若是執行失敗回滾 $conn->rollback(); echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } else { $sql = "INSERT INTO MyGuests VALUES(?, ?, ?)"; // 爲 mysqli_stmt_prepare() 初始化statement 對象 $stmt = mysqli_stmt_init($conn); //預處理語句 if (mysqli_stmt_prepare($stmt, $sql)) { // 綁定參數 mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email); // 設置參數並執行 $firstname = 'John'; $lastname = 'Doe'; $email = 'john@example.com'; mysqli_stmt_execute($stmt); $firstname = 'Mary'; $lastname = 'Moe'; $email = 'mary@example.com'; mysqli_stmt_execute($stmt); $firstname = 'Julie'; $lastname = 'Dooley'; $email = 'julie@example.com'; mysqli_stmt_execute($stmt); } } ?>
參數綁定
mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email);
該函數綁定參數查詢並將參數傳遞給數據庫。第二個參數是 "sss" 。如下列表展現了參數的類型。
預處理:建立 SQL 語句模板併發送到數據庫。預留的值使用參數 '?' 標記 。數據庫解析,編譯,對SQL語句模板執行查詢優化,並存儲結果不輸出。最後,將應用綁定的值傳遞給參數("?" 標記),數據庫執行語句
相對直接執行SQL語句,預處理的優勢:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } // 預處理及綁定 $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // 設置參數並執行 $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "新記錄插入成功"; $stmt->close(); $conn->close(); ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 設置 PDO 錯誤模式爲異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 預處理 SQL 並綁定參數 $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt->bindParam(':firstname', $firstname); $stmt->bindParam(':lastname', $lastname); $stmt->bindParam(':email', $email); // 插入行 $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); // 插入其餘行 $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); // 插入其餘行 $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "新記錄插入成功"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 建立鏈接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測鏈接 if ($conn->connect_error) { die("鏈接失敗: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 輸出每行數據 while($row = $result->fetch_assoc()) { echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]; } } else { echo "0 個結果"; } $conn->close(); ?>
<?php echo "<table style='border: solid 1px black;'>"; echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>Email</th><th>Reg date</th> </tr>"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>"; } function beginChildren() { echo "<tr>"; } function endChildren() { echo "</tr>" . "\n"; } } $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT * FROM MyGuests"); $stmt->execute(); // 設置結果集爲關聯數組 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } $dsn = null; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo "</table>"; ?>
WHERE 子句用於提取知足指定標準的的記錄。
語法:
SELECT column_name(s) FROM table_name WHERE column_name operator value
例子:
<?php $con=mysqli_connect("localhost","username","password","database"); // 檢測鏈接 if (mysqli_connect_errno()) { echo "鏈接失敗: " . mysqli_connect_error(); } $sql = "SELECT * FROM Persons WHERE FirstName='Peter'"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br>"; } ?>
ORDER BY 關鍵詞用於對記錄集中的數據進行排序,默認爲升序。
語法:
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
例子:
<?php $con=mysqli_connect("localhost","username","password","database"); // 檢測鏈接 if (mysqli_connect_errno()) { echo "鏈接失敗: " . mysqli_connect_error(); } $sql = "SELECT * FROM Persons ORDER BY age"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br>"; } mysqli_close($con); ?>
根據兩列進行排序
能夠根據多個列進行排序.
當按照多個列進行排序時,只有第一列的值相同時才使用第二列:
SELECT column_name(s) FROM table_name ORDER BY column1, column2
UPDATE 語句用於更新數據庫表中已存在的記錄。
語法:
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
注意:若是省去 WHERE 子句,全部的記錄都會被更新!
假設已經建立了「Person表」:
FirstName | LastName | Age |
---|---|---|
Peter | Griffin | 35 |
Glenn | Quagmire | 33 |
對Person表更新
<?php $con=mysqli_connect("localhost","username","password","database"); // 檢測鏈接 if (mysqli_connect_errno()) { echo "鏈接失敗: " . mysqli_connect_error(); } $sql = "UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'"; mysqli_query($con,$sql); mysqli_close($con); ?>
更新後:
FirstName | LastName | Age |
---|---|---|
Peter | Griffin | 36 |
Glenn | Quagmire | 33 |
DELETE 語句用於從數據庫表中刪除行。
語法:
DELETE FROM table_name WHERE some_column = some_value
注意:若是省去 WHERE 子句,全部的記錄都會被刪除!
假設有表Person
FirstName | LastName | Age |
---|---|---|
Peter | Griffin | 35 |
Glenn | Quagmire | 33 |
下面的例子刪除 "Persons" 表中全部 LastName='Griffin' 的記錄:
<?php $con=mysqli_connect("localhost","username","password","database"); // 檢測鏈接 if (mysqli_connect_errno()) { echo "鏈接失敗: " . mysqli_connect_error(); } $sql = "DELETE FROM Persons WHERE LastName='Griffin'"; mysqli_query($con,$sql); mysqli_close($con); ?>
刪除數據後:
FirstName | LastName | Age |
---|---|---|
Glenn | Quagmire | 33 |