Prepared Statements are an important means to ensure data security and improve efficiency when using MySQLi extensions in PHP. This article will introduce in detail the correct usage of the mysqli::stmt_init function and prepare() method, and analyze it in combination with actual examples.
mysqli::stmt_init is a method provided by MySQLi to initialize an empty mysqli_stmt (statement) object. This object can then be used to preprocess SQL statements.
The syntax is as follows:
mysqli_stmt mysqli::stmt_init ( void )
It is usually used with the prepare() method to prepare SQL statements.
The prepare() method is used to prepare a SQL statement that will be executed later and can be bound using parameter. This can effectively prevent SQL injection attacks.
The syntax is as follows:
bool mysqli_stmt::prepare ( string $query )
Here is the standard process using mysqli::stmt_init and prepare() :
Connect to the database
Initialize the preprocessing statement object
Prepare statement using prepare()
Bind parameters (if any)
Execution statement
Get the result (if it is a query statement)
Close statements and connections
Suppose we have a user table users with fields: id , username , email . We want to query the user's email address based on the user name.
<?php
// first step:Establish a database connection
$mysqli = new mysqli("localhost", "db_user", "db_password", "db_name");
// Check if the connection is successful
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Step 2:Initialize the preprocessing statement object
$stmt = $mysqli->stmt_init();
// Step 3:Prepare SQL Statement
$sql = "SELECT email FROM users WHERE username = ?";
if (!$stmt->prepare($sql)) {
die("SQL Preprocessing failed: " . $stmt->error);
}
// Step 4:Bind parameters
$username = "testuser";
$stmt->bind_param("s", $username); // "s" Represents the string type
// Step 5:执行Statement
$stmt->execute();
// Step 6:Bind the results and get the data
$stmt->bind_result($email);
if ($stmt->fetch()) {
echo "User email is: " . $email;
} else {
echo "This user was not found。";
}
// Step 7:关闭Statement与连接
$stmt->close();
$mysqli->close();
?>
Although SQL can be executed directly using the query() method, this is vulnerable to SQL injection attacks. Binding prepare() and parameter can effectively prevent this problem.
stmt_init() creates an empty statement object, and prepare() loads the SQL template into it. You can also skip stmt_init() and directly call $mysqli->prepare() to complete initialization and preparation in one step.
Yes, as long as the SQL template structure is consistent, the statement object can be reused and the bound parameters can be changed.
The following example demonstrates how to submit data through a form and insert it safely into the database:
<?php
$mysqli = new mysqli("localhost", "db_user", "db_password", "db_name");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"] ?? "";
$email = $_POST["email"] ?? "";
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO users (username, email) VALUES (?, ?)")) {
$stmt->bind_param("ss", $username, $email);
if ($stmt->execute()) {
echo "User registration successfully!";
} else {
echo "Execution failed:" . $stmt->error;
}
$stmt->close();
}
}
$mysqli->close();
?>
<form method="POST" action="https://m66.net/register.php">
username:<input type="text" name="username" required><br>
Mail:<input type="email" name="email" required><br>
<input type="submit" value="register">
</form>
The combination of mysqli::stmt_init and prepare() provides a powerful database security mechanism for PHP. Parameter binding not only prevents SQL injection, but also improves execution efficiency. In actual development, it is recommended to always use preprocessing statements to operate the database.
Want to continue to learn more about the advanced usage of bind_param() and bind_result() in MySQLi?