PHP如何使用mysqli_real_escape_string()函数?用法示例

mysqli_real_escape_string()函数是PHP中的内置函数, 用于转义全部特殊字符以用于SQL查询。在将字符串插入数据库以前使用它, 由于它删除了可能干扰查询操做的任何特殊字符。php

当使用简单的字符串时, 它们中可能包含特殊字符, 例如反斜杠和撇号(尤为是当它们直接从输入了此类数据的表单中获取数据时)。这些被认为是查询字符串的一部分, 而且会干扰其正常运行。html

<?php
  
$connection = mysqli_connect(
     "localhost" , "root" , "" , "Persons" ); 
         
// Check connection 
if (mysqli_connect_errno()) { 
     echo "Database connection failed." ; 
} 
   
$firstname = "Robert'O" ;
$lastname = "O'Connell" ;
   
$sql ="INSERT INTO Persons (FirstName, LastName) 
             VALUES ( '$firstname' , '$lastname' )";
   
   
if (mysqli_query( $connection , $sql )) {
      
     // Print the number of rows inserted in
     // the table, if insertion is successful
     printf( "%d row inserted.n" , $mysqli ->affected_rows);
}
else {
      
     // Query fails because the apostrophe in 
     // the string interferes with the query
     printf( "An error occurred!" );
}
   
?>

在上面的代码中, 查询失败, 由于使用mysqli_query()执行撇号时, 会将撇号视为查询的一部分。解决方案是在查询中使用字符串以前使用mysqli_real_escape_string()。mysql

<?php
   
$connection = mysqli_connect(
         "localhost" , "root" , "" , "Persons" ); 
  
// Check connection 
if (mysqli_connect_errno()) { 
     echo "Database connection failed." ; 
} 
       
$firstname = "Robert'O" ;
$lastname = "O'Connell" ;
   
// Remove the special characters from the
// string using mysqli_real_escape_string
   
$lastname_escape = mysqli_real_escape_string(
                     $connection , $lastname );
                      
$firstname_escape = mysqli_real_escape_string(
                     $connection , $firstname );
   
$sql ="INSERT INTO Persons (FirstName, LastName)
             VALUES ( '$firstname' , '$lastname' )";
  
if (mysqli_query( $connection , $sql )) {
      
     // Print the number of rows inserted in
     // the table, if insertion is successful
     printf( "%d row inserted.n" , $mysqli ->affected_rows);
}
   
?>

输出以下:sql

1 row inserted.

更多数据库相关内容请参考:lsbin - IT开发技术https://www.lsbin.com/数据库

查看如下更多数据库相关的内容:函数