Instructions for PHP5 mysqli prepare prepared statements

  • 2020-05-14 05:13:31
  • OfStack

mysqli's support for prepare is great for high-traffic websites, greatly reducing overhead, and ensuring the stability and security of creating queries. prepare prepared statements are divided into binding parameters and binding results, which are described in 11 below!
(1) bind parameters
See the php code below:

 
<?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 1 Three prepared query statements : 
* ? It's a wildcard , Can be used in any data that has text  
*  The equivalent of 1 A template, that is, preparation sql statements  
*/ 
if ($stmt = $mysqli->prepare("insert into `vol_msg`(mid,content) values(?,?)")){ 
/* The first 1 Three parameters are the binding type, "s" Refers to the 1 A string , It can also be "i" means int . It can also be "db" .  
* d Stands for double precision and floating point type, and b On behalf of blob type , The first 2 Three parameters are variables  
*/ 
$stmt->bind_param("is",$id,$content); 
// Assign a value to a variable  
$id = ""; 
$content = " That's what you're inserting "; 
// Execute prepare statement  
$stmt->execute(); 
// Displays the inserted statement  
echo "Row inserted".$stmt->affected_rows; 
// You can continue to add multiple statements without the need prepare The precompiled  
// Close the link to the database  
$mysqli->close(); 
} 
?> 

The running results of the above php instance:
Row inserted:1
(2). Binding result: the binding result is to give the fields you bind to php variables so that they can be used if necessary
See the php code below:
 
<?php 
// Create a connection  
$mysqli=new mysqli("localhost","root","","volunteer"); 
// Set up the mysqli coding  
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 prepared statements  
if ($stmt = $mysqli->prepare("select mid,content from `vol_msg`")){ 
// Execute the query  
$stmt->execute(); 
// Bind the actual variables for the prepared statement  
$stmt->bind_result($id,$content); 
// A variable that displays the result of the binding  
while($stmt->fetch()){ 
echo " The first ".$id." Article:  ".$content."<br />"; 
} 
// Close the link to the database  
$mysqli->close(); 
} 
?> 


Related articles: