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

PHP + MySQLi 预处理语句实现批量增删改:原理、代码与性能优势

     編輯:PHP 綜合知識

为什么用预处理?

批量插入 100 条数据,普通方式发送 100 次 SQL,MySQL 需解析、编译、优化、执行 100 次。预处理:

  1. 第一次发送含占位符 ? 的 SQL,MySQL 编译生成执行计划
  2. 后续 99 次仅发送参数数据,复用执行计划,**省去编译开销**
  3. 天然防 SQL 注入(参数与代码分离)

完整示例:批量插入

<?php
$mysqli = new MySQLi('localhost', 'root', '123456', 'test');
if ($mysqli->connect_error) die($mysqli->connect_error);
$mysqli->set_charset('utf8mb4');

$sql = 'INSERT INTO account (id, balance) VALUES (?, ?)'; // id 自增传 null
$stmt = $mysqli->prepare($sql); // 编译阶段

// 第一条
$id = null; $balance = 100.5;
$stmt->bind_param('id', $id, $balance); // 'i'=int, 'd'=double
$stmt->execute() or die('Insert failed: ' . $stmt->error);

// 第二条
$balance = 400.3;
$stmt->bind_param('id', $id, $balance); // 重新绑定新值
$stmt->execute() or die('Insert failed: ' . $stmt->error);

$stmt->close();
$mysqli->close();
?>

bind_param 类型字符对照表

字符对应 PHP 类型
iinteger
ddouble/float
sstring
bblob (需配合 send_long_data)

批量更新/删除

<?php
// 更新
$upd = $mysqli->prepare('UPDATE account SET balance = ? WHERE id = ?');
$upd->bind_param('di', $bal, $id);
foreach ($data as $row) {
    $bal = $row['balance']; $id = $row['id'];
    $upd->execute();
}

// 删除
$del = $mysqli->prepare('DELETE FROM account WHERE id = ?');
$del->bind_param('i', $id);
foreach ($ids as $id) { $del->execute(); }
?>

性能对比(万级数据)

方式耗时(约)网络往返
普通 query 循环2.5s10,000 次
预处理 + 循环 execute0.8s10,000 次
预处理 + 单条多值 INSERT0.15s1 次

极致性能:INSERT INTO t (a,b) VALUES (?,?), (?,?), ... 单次多值绑定,需动态生成占位符字符串。

注意事项

  • prepare() 失败返回 false,需检查 $mysqli->error
  • bind_param 参数**必须是变量**,不能直接传表达式/字面量
  • 事务包裹批量操作:$mysqli->begin_transaction() ... commit()
  • 大批量建议关闭自动提交 $mysqli->autocommit(false)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved