PHP mysqli real_escape_string() 函数
示例 - 面向对象的样式
转义字符串中的特殊字符:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " .
$mysqli -> connect_error;
exit();
}
// Escape special characters, if any
$firstname = $mysqli -> real_escape_string($_POST['firstname']);
$lastname = $mysqli -> real_escape_string($_POST['lastname']);
$age =
$mysqli -> real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
$mysqli -> close();
?>
查看底部的程序样式示例。
定义和用法
real_escape_string() / mysqli_real_escape_string() 函数将字符串中的特殊字符转义以用于 SQL 查询,同时考虑到连接的当前字符集。
此函数用于创建可用于 SQL 语句的合法 SQL 字符串。 假设我们有以下代码:
<?php
$lastname = "D'Ore";
$sql="INSERT INTO Persons (LastName) VALUES ('$lastname')";
// This query will fail, cause we didn't escape $lastname
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
?>
语法
面向对象的风格:
$mysqli ->
real_escape_string(escapestring)
程序风格:
mysqli_real_escape_string(connection, escapestring)
参数值
参数 | 描述 |
---|---|
connection | 必需。规定要使用的 MySQL 连接。 |
escapestring | 必需。要转义的字符串。编码的字符是 NUL(ASCII 0)、\n、\r、\、'、" 和 Control-Z。 |
技术细节
返回值: | 返回已转义的字符串。 |
---|---|
PHP 版本: | 5+ |
示例 - 程序样式
转义字符串中的特殊字符:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Escape special characters, if any
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con, $sql))
{
printf("%d Row inserted.\n", mysqli_affected_rows($con));
}
mysqli_close($con);
?>
❮ PHP MySQLi 参考手册