PHP怎么使用mysqli_real_escape_string()函数

发布时间:2021-06-07 09:49:48 作者:小新
来源:亿速云 阅读:218

这篇文章主要为大家展示了“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()函数”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. 极速赛车源码搭建 PHP中的防御性编程
  2. PHP phar:协议对象注入技术介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:怎么使用phpstorm自带服务器运行php项目

下一篇:PHP中怎么使用Ds\Vector copy()函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》