ホームページ  >  記事  >  バックエンド開発  >  PHP で mysqli_real_escape_string() 関数を使用するにはどうすればよいですか?

PHP で mysqli_real_escape_string() 関数を使用するにはどうすればよいですか?

醉折花枝作酒筹
醉折花枝作酒筹転載
2021-06-04 17:34:303930ブラウズ

この記事では、PHP で mysqli_real_escape_string() 関数を使用する方法を紹介します。一定の参考値があるので、困っている友達が参考になれば幸いです。

PHP で mysqli_real_escape_string() 関数を使用するにはどうすればよいですか?

mysqli_real_escape_string() 関数は、SQL クエリで使用するすべての特殊文字をエスケープするために使用される PHP の組み込み関数です。クエリ操作を妨げる可能性のある特殊文字が削除されるため、データベースに文字列を挿入する前にこれを使用します。

単純な文字列を使用する場合、バックスラッシュやアポストロフィなどの特殊文字が含まれる場合があります (特に、データが入力されたフォームから直接データを取得する場合)。これらはクエリ文字列の一部とみなされ、その適切な機能を妨げます。

<?php
  
$connection = mysqli_connect(
     "localhost" , "root" , "" , "Persons" ); 
         
// Check connection 
if (mysqli_connect_errno()) { 
     echo "Database connection failed." ; 
} 
   
$firstname = "Robert&#39;O" ;
$lastname = "O&#39;Connell" ;
   
$sql ="INSERT INTO Persons (FirstName, LastName) 
             VALUES ( &#39;$firstname&#39; , &#39;$lastname&#39; )";
   
   
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&#39;O" ;
$lastname = "O&#39;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 ( &#39;$firstname&#39; , &#39;$lastname&#39; )";
  
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() 関数を使用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はsegmentfault.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。