Introduction of prepare Operation Database Using mysqli in PHP5

  • 2021-12-04 09:40:41
  • OfStack

The support of mysqli to prepare in php5 is very beneficial for websites with large visits, greatly reducing system overhead, and ensuring the stability and security of creating queries.

After PHP5.0, we can use mysqli. The support of mysqli to prepare is very beneficial to websites with large visits, especially the support of transactions, which will greatly reduce the system overhead, ensure the stability and security of creating queries, and effectively prevent SQL injection attacks.

prepare preparation statements are divided into binding parameters and binding results. Next, introduce it in detail.

1. Binding parameters

Look at the following php code:


<?php 
// Create a connection  
$mysqli=new mysqli("localhost","root","","123456"); 
// Check whether the connection is created  
if (mysqli_connect_errno()) { 
 printf("Connect failed: %s\n", mysqli_connect_error()); 
 exit(); 
}
/** 
 *  Create 1 Prepare query statements : 
 * ? It's a wildcard , Can be used in any data with text  
 *  Equivalent to 1 Template, that is, prepare sql Statement  
 */ 
if ($stmt = $mysqli->prepare("insert into `codetc_msg`(mid,content) values(?,?)")){ 
 /**
 *  No. 1 1 Parameters are binding types, "is" It refers to the above SQL In the statement 1 A ? The parameter is int Type, type 2 A ? The parameter is string Type  
 *  Among them i Refer to int , s Refer to string ,   Except for i , s Besides, there are d Represents a double-precision floating-point type, b Representative blod Type, etc 
 */ 
 $stmt->bind_param("is",$id,$content); 
 // Assign a value to a variable  
 $id = 1; 
 $content = " This is what was inserted "; 
 // Execute the preparation statement  
 $stmt->execute(); 
 // Display the number of affected rows inserted 
 echo "Row inserted".$stmt->affected_rows; 
 // Close the link to the database  
 $mysqli->close(); 
} 
?> 

2. Binding result: The binding result is to give the fields you bind to php variables so that these variables can be used when necessary

Look at the following php code:


<?php 
// Create a connection  
$mysqli=new mysqli("localhost","root","","123456"); 
// Settings mysqli Code  
mysqli_query($mysqli,"SET NAMES utf8"); 
// Check whether the connection is created  
if (mysqli_connect_errno()) { 
 printf("Connect failed: %s\n", mysqli_connect_error()); 
 exit(); 
} 
// Create a preparation statement  
if ($stmt = $mysqli->prepare("select mid,content from `codetc_msg`")){ 
 // Execute a query  
 $stmt->execute(); 
 // Bind actual variables for prepared statements  
 $stmt->bind_result($id,$content); 
 // Variables that display binding results  
 while($stmt->fetch()){ 
 echo " No. 1 ".$id." Article:  ".$content."<br>"; 
 } 
 // Close the link to the database  
 $mysqli->close(); 
} 
?>

Summarize


Related articles: