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/數據庫

查看如下更多數據庫相關的內容:函數

相關文章
相關標籤/搜索