mysqli
是 PHP 中用于連接和操作 MySQL 數(shù)據(jù)庫的擴(kuò)展。在復(fù)雜查詢中,mysqli
提供了許多功能,如預(yù)處理語句、事務(wù)處理和存儲(chǔ)過程等,以提高查詢的安全性和性能。
mysqli
預(yù)處理語句的示例:$mysqli = new mysqli("localhost", "username", "password", "database");
$stmt = $mysqli->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
$username = "JohnDoe";
$email = "john.doe@example.com";
$stmt->execute();
$stmt->close();
$mysqli->close();
mysqli
事務(wù)處理的示例:$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->autocommit(false); // 關(guān)閉自動(dòng)提交,開始事務(wù)
$stmt1 = $mysqli->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
$stmt1->bind_param("di", $amount, $user_id);
$amount = 100;
$user_id = 1;
$stmt1->execute();
$stmt2 = $mysqli->prepare("UPDATE accounts SET balance = balance + ? WHERE user_id = ?");
$stmt2->bind_param("di", $amount, $user_id);
$stmt2->execute();
if ($stmt1 && $stmt2) {
$mysqli->commit(); // 提交事務(wù)
} else {
$mysqli->rollback(); // 回滾事務(wù)
}
$stmt1->close();
$stmt2->close();
$mysqli->close();
mysqli
調(diào)用存儲(chǔ)過程的示例:$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$result = $mysqli->query("CALL get_user_data(?, ?)");
$result->bind_param("is", $user_id, $username);
$user_id = 1;
$username = "";
while ($row = $result->fetch_assoc()) {
echo "User ID: " . $row["id"] . ", Username: " . $row["username"] . "<br>";
}
$result->close();
$mysqli->close();
總之,mysqli
函數(shù)在復(fù)雜查詢中的應(yīng)用包括預(yù)處理語句、事務(wù)處理和存儲(chǔ)過程等,這些功能可以提高查詢的安全性和性能。在實(shí)際開發(fā)中,根據(jù)需求選擇合適的 mysqli
功能來實(shí)現(xiàn)高效、安全的數(shù)據(jù)庫操作。