PHP如何使用mysqli_real_escape_string()函数?

 4023

本篇文章给大家介绍一下PHP使用mysqli_real_escape_string()函数的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。


PHP如何使用mysqli_real_escape_string()函数?


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

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

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

  1. <?php
  2.    
  3. $connection = mysqli_connect(
  4.      "localhost" , "root" , "" , "Persons" ); 
  5.           
  6. // Check connection 
  7. if (mysqli_connect_errno()) { 
  8.      echo "Database connection failed." ; 
  9. } 
  10.     
  11. $firstname = "Robert'O" ;
  12. $lastname = "O'Connell" ;
  13.     
  14. $sql ="INSERT INTO Persons (FirstName, LastName) 
  15.              VALUES ( '$firstname' , '$lastname' )";
  16.     
  17.     
  18. if (mysqli_query( $connection , $sql )) {
  19.        
  20.      // Print the number of rows inserted in
  21.      // the table, if insertion is successful
  22.      printf( "%d row inserted.n" , $mysqli ->affected_rows);
  23. }
  24. else {
  25.        
  26.      // Query fails because the apostrophe in 
  27.      // the string interferes with the query
  28.      printf( "An error occurred!" );
  29. }
  30.     
  31. ?>

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

  1. <?php
  2.     
  3. $connection = mysqli_connect(
  4.          "localhost" , "root" , "" , "Persons" ); 
  5.    
  6. // Check connection 
  7. if (mysqli_connect_errno()) { 
  8.      echo "Database connection failed." ; 
  9. } 
  10.         
  11. $firstname = "Robert'O" ;
  12. $lastname = "O'Connell" ;
  13.     
  14. // Remove the special characters from the
  15. // string using mysqli_real_escape_string
  16.     
  17. $lastname_escape = mysqli_real_escape_string(
  18.                      $connection , $lastname );
  19.                        
  20. $firstname_escape = mysqli_real_escape_string(
  21.                      $connection , $firstname );
  22.     
  23. $sql ="INSERT INTO Persons (FirstName, LastName)
  24.              VALUES ( '$firstname' , '$lastname' )";
  25.    
  26. if (mysqli_query( $connection , $sql )) {
  27.        
  28.      // Print the number of rows inserted in
  29.      // the table, if insertion is successful
  30.      printf( "%d row inserted.n" , $mysqli ->affected_rows);
  31. }
  32.     
  33. ?>

输出如下:

  1. 1 row inserted.


TAG标签:
本文网址:https://www.zztuku.com/detail-8925.html
站长图库 - PHP如何使用mysqli_real_escape_string()函数?
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐