mysqli 預處理(Prepared Statements)是防範 SQL 注入、提升重複執行效能的核心技術。本文通過「批量新增用戶」與「條件查詢」兩個實戰案例,詳細講解 prepare、bind_param、bind_result、execute 等核心 API 的用法。
prepare(sql) 建立預編譯對象bind_param(type, vars...) 綁定參數(類型須與佔位符一一對應)execute() 執行bind_result() 綁定結果集 → fetch() 逐行取值free_result()、close()<?php
$mysqli = new MySQLi("localhost", "root", "root", "test");
if ($mysqli->connect_error) die($mysqli->connect_error);
$sql = "INSERT INTO user1(name, password, email, age) VALUES (?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
// 綁定參數類型:s=string, i=integer
$stmt->bind_param("sssi", $name, $password, $email, $age);
// 第 1 條
$name = "小芳"; $password = "123456"; $email = "xiaofang@126.com"; $age = 18;
$stmt->execute();
// 第 2 條
$name = "小楊"; $password = "123456"; $email = "xiaoyang@126.com"; $age = 18;
$stmt->execute();
// 第 3 條
$name = "小G"; $password = "123456"; $email = "xiaoG@126.com"; $age = 18;
$stmt->execute();
echo $stmt->error ? "失敗:" . $stmt->error : "成功";
$stmt->close(); $mysqli->close();
?>
<?php
$mysqli = new MySQLi("localhost", "root", "root", "test");
$stmt = $mysqli->prepare("SELECT id, name, email FROM user1 WHERE id > ?");
$id = 5;
$stmt->bind_param("i", $id);
$stmt->bind_result($id, $name, $email);
$stmt->execute();
while ($stmt->fetch()) {
echo "<br>$id--$name--$email";
}
$stmt->free_result();
$stmt->close();
$mysqli->close();
?>
? 讓 SQL 結構清晰可見bind_param 類型字串(如 "sssi")必須與參數個數、順序嚴格對應bind_result 並循環 fetch() 取值finally 或流程末尾釋放 stmt 與 conn