mysqli_real_escape_string()
实例
转义字符串中的特殊字符:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE myPersons LIKE Persons");
$newpers="Da‘Silva"
// This query will fail, cause we did not escape $newpers
mysqli_query($con,"INSERT into myPersons (Lastname) VALUES (‘$newpers‘)");
$newpers=mysqli_real_escape_string($con,$newpers);
// This query will work, cause we escaped $newpers
mysqli_query($con,"INSERT into myPersons (Lastname) VALUES (‘$newpers‘)");
mysqli_close($con);
?>
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE myPersons LIKE Persons");
$newpers="Da‘Silva"
// This query will fail, cause we did not escape $newpers
mysqli_query($con,"INSERT into myPersons (Lastname) VALUES (‘$newpers‘)");
$newpers=mysqli_real_escape_string($con,$newpers);
// This query will work, cause we escaped $newpers
mysqli_query($con,"INSERT into myPersons (Lastname) VALUES (‘$newpers‘)");
mysqli_close($con);
?>
定义和用法
mysqli_real_escape_string() 函数转义在 SQL 语句中使用的字符串中的特殊字符。
语法
mysqli_real_escape_string(connection,escapestring);
参数 | 描述 |
---|---|
connection | 必需。规定要使用的 MySQL 连接。 |
escapestring | 必需。要转义的字符串。编码的字符是 NUL(ASCII 0)、\n、\r、\、‘、" 和 Control-Z。 |
技术细节
返回值: | 返回已转义的字符串。 |
---|---|
PHP 版本: | 5+ |