When using PHP to operate MySQL databases, the mysqli extension provides rich preprocessing statements (Prepared Statements) support, which can effectively prevent SQL injection attacks and improve the security and efficiency of database operations. This article will focus on how to initialize a statement object using the mysqli::stmt_init method and execute SQL statements through the object.
mysqli::stmt_init() is a method of the mysqli class that is used to initialize an empty statement object ( mysqli_stmt ). This object can be bound to SQL query statements by calling prepare() method and further called bind_param() , execute() and other methods for operation.
The basic syntax is as follows:
$stmt = $mysqli->stmt_init();
where $mysqli is a mysqli object that has been connected to the database.
Here is a complete PHP example using stmt_init initialization statement and executing SQL queries:
<?php
// Database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check the connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Initialize statement object
$stmt = $mysqli->stmt_init();
// Preprocessing SQL Statement
if ($stmt->prepare("SELECT name, email FROM users WHERE id = ?")) {
// Bind parameters
$id = 1;
$stmt->bind_param("i", $id);
// 执行Statement
$stmt->execute();
// Binding result variables
$stmt->bind_result($name, $email);
// Get query results
while ($stmt->fetch()) {
echo "Username: $name, Mail: $email<br>";
}
// 关闭Statement
$stmt->close();
} else {
echo "SQL Preprocessing失败: " . $stmt->error;
}
// Close the connection
$mysqli->close();
?>
After calling stmt_init() , you must use the prepare() method to actually bind the SQL statement.
The type parameters in bind_param(), for example, "i" represents an integer, and "s" represents a string, must be set correctly.
Be sure to call $stmt->close() after using the statement object to free up the resource.
Although you can directly use $mysqli->prepare() for statement preparation, stmt_init() provides more detailed control, such as more useful when you need to check whether the statement is reusable or use a low-level interface.