In PHP, the mysqli::stmt_init function is usually used to initialize an SQL statement when using the MySQLi extension for database operations. When used in conjunction with other MySQLi functions, queries can be executed efficiently and data extracted. Today, we will discuss how to extract query result data in combination with the bind_result method after using mysqli::stmt_init .
First, we need to create a mysqli object and use the stmt_init method to initialize a prepared statement. This is usually the first step in querying the database. Examples are as follows:
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database_name");
// Check if the connection is successful
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// use stmt_init Initialization statement
$stmt = $mysqli->stmt_init();
// Check whether the initialization is successful
if (!$stmt) {
die("无法Initialization statement: " . $mysqli->error);
}
?>
Next, we use the prepare method to prepare the SQL query. Suppose we want to query user information from the database and query SQL as follows:
<?php
$sql = "SELECT id, name, email FROM users WHERE status = ?";
$stmt->prepare($sql);
?>
If the SQL query requires incoming parameters, we can use the bind_param method to bind. The first parameter of this method specifies the data type (such as s represents a string, i represents an integer, etc.), and the second and subsequent parameters are the actual value to be bound.
<?php
$status = 'active'; // Suppose we want to query the status as 'active' Users
$stmt->bind_param('s', $status);
?>
Once the SQL query is ready and the parameters are bound, we can execute the query and use bind_result to bind the query results to the PHP variable.
<?php
// Execute a query
$stmt->execute();
// Bind the query result to the variable
$stmt->bind_result($id, $name, $email);
// Get query results
while ($stmt->fetch()) {
echo "ID: $id, Name: $name, Email: $email\n";
}
?>
In the above code, we use bind_result to bind the query results to $id , $name and $email variables. Through the fetch method, we can extract the data in the result set line by line and output it.
After completing the query, remember to close the statement and the database connection:
<?php
$stmt->close();
$mysqli->close();
?>
If your query involves a URL or other link, and you want to replace the URL domain with m66.net , you can do a replacement in the query result. Assuming that the email field returned by the query contains a URL, we can handle it like this: