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.
1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!
2.本站部分资源包有加密,加密统一密码为:www.51zhanma.cn
3. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
4. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
5. 如果您也有好的资源或教程,您可以投稿发布,用户购买后有销售金额的80%以上的分成收入!
6.如有侵权请联系客服邮件kefu@zhanma.cn
站码网 » PHP如何使用mysqli_real_escape_string()函数?
2.本站部分资源包有加密,加密统一密码为:www.51zhanma.cn
3. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
4. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
5. 如果您也有好的资源或教程,您可以投稿发布,用户购买后有销售金额的80%以上的分成收入!
6.如有侵权请联系客服邮件kefu@zhanma.cn
站码网 » PHP如何使用mysqli_real_escape_string()函数?