mysqli
是 PHP 中用于连接和操作 MySQL 数据库的扩展。在复杂查询中,mysqli
提供了许多功能,如预处理语句、事务处理和存储过程等,以提高查询的安全性和性能。
mysqli
预处理语句的示例:$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
事务处理的示例:$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->autocommit(false); // 关闭自动提交,开始事务
$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(); // 提交事务
} else {
$mysqli->rollback(); // 回滚事务
}
$stmt1->close();
$stmt2->close();
$mysqli->close();
mysqli
调用存储过程的示例:$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
函数在复杂查询中的应用包括预处理语句、事务处理和存储过程等,这些功能可以提高查询的安全性和性能。在实际开发中,根据需求选择合适的 mysqli
功能来实现高效、安全的数据库操作。