溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP怎么使用mysqli_real_escape_string()函數

發布時間:2021-06-07 09:49:48 來源:億速云 閱讀:266 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“PHP怎么使用mysqli_real_escape_string()函數”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“PHP怎么使用mysqli_real_escape_string()函數”這篇文章吧。

PHP如何使用mysqli_real_escape_string()函數?

mysqli_real_escape_string()函數是PHP中的內置函數, 用于轉義所有特殊字符以用于SQL查詢。在將字符串插入數據庫之前使用它, 因為它刪除了可能干擾查詢操作的任何特殊字符。

當使用簡單的字符串時, 它們中可能包含特殊字符, 例如反斜杠和撇號(尤其是當它們直接從輸入了此類數據的表單中獲取數據時)。這些被認為是查詢字符串的一部分, 并且會干擾其正常運行。

<?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()。

<?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);
}
   
?>

輸出如下:

1 row inserted.

以上是“PHP怎么使用mysqli_real_escape_string()函數”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

php
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女