| 代碼 | 對應 PHP 類型 | MySQL 類型示例 |
| i | integer | INT, TINYINT, BIGINT |
| d | double | FLOAT, DOUBLE, DECIMAL |
| s | string | VARCHAR, TEXT, DATE, BLOB |
| b | blob (字符串) | BLOB, BINARY (需配合 send_long_data) |
常用 SQL 操作封裝
查詢構建器模式
function query($mysqli, $sql, $types = '', ...$params) {
$stmt = $mysqli->prepare($sql);
if ($types && $params) {
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result(); // 需 mysqlnd
return $result->fetch_all(MYSQLI_ASSOC);
}
// 使用
$users = query($mysqli, "SELECT * FROM users WHERE status = ? AND age > ?", 'si', 1, 18);
插入獲取自增 ID
$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param('ss', $name, $email);
$stmt->execute();
$userId = $stmt->insert_id; // 關鍵:獲取自增 ID
$stmt->close();
受影響行數
$affected = $stmt->affected_rows; // INSERT/UPDATE/DELETE 後可用
事務處理:保證數據一致性
try {
$mysqli->begin_transaction(); // 或 $mysqli->autocommit(false);
// 操作 1
$stmt1 = $mysqli->prepare("INSERT INTO orders (user_id, amount) VALUES (?, ?)");
$stmt1->bind_param('id', $uid, $amount);
$stmt1->execute();
if ($stmt1->affected_rows !== 1) throw new Exception("訂單創建失敗");
$orderId = $stmt1->insert_id;
// 操作 2
$stmt2 = $mysqli->prepare("UPDATE accounts SET balance = balance - ? WHERE user_id = ?");
$stmt2->bind_param('di', $amount, $uid);
$stmt2->execute();
if ($stmt2->affected_rows !== 1) throw new Exception("扣款失敗");
// 提交
$mysqli->commit();
echo "事務成功";
} catch (Exception $e) {
$mysqli->rollback();
echo "事務回滾: " . $e->getMessage();
} finally {
$mysqli->autocommit(true); // 恢復自動提交
}
多語句執行
$sql = "DROP TABLE IF EXISTS tmp; CREATE TABLE tmp (id INT); INSERT INTO tmp VALUES (1),(2);";
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
// 處理結果集
$result->free();
}
} while ($mysqli->next_result());
}
錯誤處理模式
// 異常模式 (推薦)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli = new mysqli(...);
// 操作...
} catch (mysqli_sql_exception $e) {
error_log("MySQL Error: " . $e->getMessage());
// 友好錯誤頁面
}
性能優化清單
- 使用預處理:重複執行同結構 SQL 只解析一次
- 批量操作:
INSERT ... VALUES (?,?),(?,?)... 配合循環綁定
- 關閉未用連接:及時
$stmt->close()、$mysqli->close()
- 持久連接:
new mysqli('p:localhost', ...) 謹慎使用,配合連接池
- 索引優化:EXPLAIN 分析慢查詢
總結
Mysqli 面向對象 API 是 PHP 操作 MySQL 的標準方式。核心掌握:預處理防注入、綁定參數類型、事務保證一致性、獲取自增 ID、異常模式錯誤處理。現代框架 (Laravel Eloquent、ThinkPHP Db、Yii ActiveRecord) 底層均基於 PDO/Mysqli 封裝,理解原理有助於高效使用 ORM 並排查性能問題。
- 上一篇文章: PHP 微信小店 API 二次開發完整類庫:商品、訂單、物流、發貨
- 下一篇文章: PHP 微信小店 API 開發完整指南:Access Token 管理、商品/分組增刪改查、cURL 封裝與錯誤處理
Copyright ©
程式碼之家 All Rights Reserved