<?php
$mysqli = new mysqli("localhost", "root", "123456", "xiaoqiangdb");
$sql = "INSERT INTO shops (name, price, num, desn) VALUES (?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql); // 1. 準備
$stmt->bind_param("sdis", $name, $price, $num, $desn); // 2. 綁定參數 (類型+變量引用)
$name = "zhangsan"; $price = 56.56; $num = 66; $desn = "good";
$stmt->execute(); // 3. 執行
echo "Last ID: " . $stmt->insert_id;
$stmt->close();
?>
類型代碼:i(int)、d(double)、s(string)、b(blob)。
<?php
$sql = "SELECT id, name, price, num, desn FROM shops WHERE id > ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $id); // 綁定輸入參數
$stmt->bind_result($id, $name, $price, $num, $desn); // 綁定輸出列(順序必須一致)
$id = 99;
$stmt->execute();
$stmt->store_result(); // 緩存結果集,才能用 num_rows/data_seek
// 字段元數據
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
echo $field->name . " ";
}
echo "<br>";
// 讀取數據
$stmt->data_seek(2); // 跳到第 3 行
while ($stmt->fetch()) {
echo "$id--$name--$price--$num--$desn<br>";
}
echo "總行數: " . $stmt->num_rows;
$stmt->free_result();
$stmt->close();
?>
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SET NAMES 'gbk'");
$stmt = $mysqli->prepare("INSERT INTO `test` (`name`,`age`,`dpc`) VALUES (?,?,?)");
$stmt->bind_param("sis", $name, $age, $dpc);
foreach (range(1,4) as $i) {
$name = "陳華$i"; $age = 25; $dpc = "web開發筆記...";
$stmt->execute();
}
echo "Last ID: " . $stmt->insert_id . "<br>";
echo "Affected: " . $stmt->affected_rows;
$stmt->close();
?>
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SET NAMES 'gbk'");
$stmt = $mysqli->prepare("SELECT * FROM `test` WHERE `id` > ?");
$stmt->bind_param("i", $id);
$id = 5;
$stmt->execute();
$stmt->bind_result($id, $name, $age, $dpc);
while ($stmt->fetch()) {
echo "$name----$age----$dpc<br>";
}
$stmt->close();
?>
| 方法 | 用途 |
|---|---|
| prepare() | 預處理 SQL,返回 stmt 對象 |
| bind_param() | 綁定輸入參數(類型字符串 + 變量引用) |
| bind_result() | 綁定輸出列到變量 |
| execute() | 執行預處理語句 |
| store_result() | 緩存結果集(必須調用才能用 num_rows/data_seek) |
| fetch() | 逐行獲取綁定結果 |
| data_seek() | 移動結果指針 |
| free_result()/close() | 釋放資源 |