首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP Mysqli 面向對象操作 MySQL 完整指南:連接、預處理、事務、最佳實踐

     編輯:PHP 綜合知識

Mysqli 核心優勢

  • 面向對象 API,代碼結構清晰
  • 預處理語句防 SQL 注入、提升性能
  • 事務支持保證數據一致性
  • 多語句執行、異步查詢等高級特性

基礎連接與配置

// php.ini 啟用擴展
extension=mysqli

// 連接數據庫
$mysqli = new mysqli('localhost', 'user', 'password', 'database', 3306);

// 檢查連接
if ($mysqli->connect_errno) {
    die("連接失敗: " . $mysqli->connect_error);
}

// 設置字符集 (防止中文亂碼)
$mysqli->set_charset('utf8mb4'); // 推薦 utf8mb4 支持 emoji

// 可選:設置時區
$mysqli->query("SET time_zone = '+08:00'");

預處理語句:核心最佳實踐

// 1. 準備 SQL (佔位符 ?)
$sql = "SELECT username, password FROM member WHERE username = ? AND password = ?";

// 2. 預處理
$stmt = $mysqli->prepare($sql);
if (!$stmt) die("預處理失敗: " . $mysqli->error);

// 3. 綁定參數 (類型字符串: i/d/s/b)
$stmt->bind_param('ss', $username, $password);

// 4. 執行
$stmt->execute();

// 5. 綁定結果變量
$stmt->bind_result($user, $pass);

// 6. 獲取數據
while ($stmt->fetch()) {
    echo "User: $user, Pass: $pass
"; } // 7. 關閉 $stmt->close(); $mysqli->close();

bind_param 類型代碼

常用 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());
    // 友好錯誤頁面
}

性能優化清單

  1. 使用預處理:重複執行同結構 SQL 只解析一次
  2. 批量操作:INSERT ... VALUES (?,?),(?,?)... 配合循環綁定
  3. 關閉未用連接:及時 $stmt->close()、$mysqli->close()
  4. 持久連接:new mysqli('p:localhost', ...) 謹慎使用,配合連接池
  5. 索引優化:EXPLAIN 分析慢查詢

總結

Mysqli 面向對象 API 是 PHP 操作 MySQL 的標準方式。核心掌握:預處理防注入、綁定參數類型、事務保證一致性、獲取自增 ID、異常模式錯誤處理。現代框架 (Laravel Eloquent、ThinkPHP Db、Yii ActiveRecord) 底層均基於 PDO/Mysqli 封裝,理解原理有助於高效使用 ORM 並排查性能問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
代碼對應 PHP 類型MySQL 類型示例
iintegerINT, TINYINT, BIGINT
ddoubleFLOAT, DOUBLE, DECIMAL
sstringVARCHAR, TEXT, DATE, BLOB
bblob (字符串)BLOB, BINARY (需配合 send_long_data)