MYSQLI support for prepare is good for a large number of Web sites, which greatly reduces system overhead and guarantees the stability and security of creating queries. Prepare prepared statements are divided into binding parameters and binding results, the following will be introduced!
(1) Binding parameters
Look at the following PHP code:
Copy Code code as follows:
<?php
Create a connection
$mysqli =new mysqli ("localhost", "root", "" "," volunteer ");
Check if the connection was created
if (Mysqli_connect_errno ()) {
printf ("Connect failed:%s\n", Mysqli_connect_error ());
Exit ();
}
/*
* Create a prepared query statement:
* is a wildcard character that can be used in any text data
* is equivalent to a template, which is to prepare SQL statements
*/
if ($stmt = $mysqli->prepare ("insert INTO ' vol_msg ' (mid,content) VALUES (?,?)") {
/* The first parameter is the binding type, and "s" refers to a string, or "I", which refers to an int. It can also be "db",
* d represents a double and a floating-point type, while B represents a BLOB type and the second argument is a variable
*/
$stmt->bind_param ("is", $id, $content);
Assigning values to variables
$id = "";
$content = "This is the inserted content";
Execute Prepare statement
$stmt->execute ();
Show inserted statements
echo "Row inserted". $stmt->affected_rows;
You can also continue to add more than one statement, you do not need to prepare precompiled
Close a link to a database
$mysqli->close ();
}
?>
Above PHP instance run result:
Row inserted:1
(2). Binding Result: The binding result is the field you bind to the PHP variable so that you can use these variables if necessary
Take a look at the following PHP code:
Copy Code code as follows:
<?php
Create a connection
$mysqli =new mysqli ("localhost", "root", "" "," volunteer ");
Set MYSQLI encoding
Mysqli_query ($mysqli, "SET NAMES UTF8");
Check if the connection was created
if (Mysqli_connect_errno ()) {
printf ("Connect failed:%s\n", Mysqli_connect_error ());
Exit ();
}
Create a prepared statement
if ($stmt = $mysqli->prepare ("Select Mid,content from ' vol_msg '")) {
Execute Query
$stmt->execute ();
Bind the actual variable for preparing the statement
$stmt->bind_result ($id, $content);
A variable that displays the result of a binding
while ($stmt->fetch ()) {
echo "section" $id. " : ". $content." <br/> ";
}
Close a link to a database
$mysqli->close ();
}
?>