PHP MySQLi 函数

PHP mysqli::escape_string() / mysqli_escape_string() 函数用于创建合法的 SQL 字符串,该字符串可以在 SQL 语句中使用。考虑到连接的当前字符集,对给定的字符串进行编码以生成转义的 SQL 字符串。

此函数是 mysqli_real_escape_string() 函数的别名。

此函数是 mysqli_real_escape_string() 函数的别名。 p>

语法

//面向对象风格
public mysqli::escape_string(string)

//面向过程风格
mysqli_escape_string(mysql, string)

参数

mysql 必需。 仅适用于面向过程风格:指定 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。
string 必填。 指定要转义的字符串。编码的字符为 NUL (ASCII 0)、\n、\r、\、'、"、和 Control-Z..

返回值

返回转义字符串。

示例:面向对象风格

下面的示例显示mysqli::escape_string()的用法

<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

$city = "N'Djamena";

//这个带有转义$city的查询将起作用
$sql = sprintf("SELECT Name, Age, Salary FROM Employee WHERE City='%s'",
                                 $mysqli->escape_string($city));
$result = $mysqli->query($sql);
printf("Select returned %d rows.\n", $result->num_rows);

//这个查询会失败,因为$city没有转义
$sql = sprintf("SELECT Name, Age, Salary FROM Employee WHERE City='%s'", $city);
$result = $mysqli->query($sql);
?>

上述代码的输出将类似于(为便于阅读而自动换行):

Select returned 6 rows.

Fatal error: Uncaught mysqli_sql_exception: You have an 
error in your SQL syntax; check the manual that corresponds 
to your MySQL server version for the right syntax to 
use near N'Djamena'' at line 1 in...

示例:面向过程风格

下面的示例显示了 mysqli_escape_string() 函数的用法。

<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

$city = "N'Djamena";

//这个带有转义$city的查询将起作用
$sql = sprintf("SELECT Name, Age, Salary FROM Employee WHERE City='%s'",
                              mysqli_escape_string($mysqli, $city));
$result = mysqli_query($mysqli, $sql);
printf("Select returned %d rows.\n", mysqli_num_rows($result));

//这个查询会失败,因为$city没有转义
$sql = sprintf("SELECT Name, Age, Salary FROM Employee WHERE City='%s'", $city);
$result = mysqli_query($mysqli, $sql);
?>

上述代码的输出将类似于(为了便于阅读而自动换行):

Select returned 6 rows.

Fatal error: Uncaught mysqli_sql_exception: You have an 
error in your SQL syntax; check the manual that corresponds 
to your MySQL server version for the right syntax to 
use near N'Djamena'' at line 1 in...