mysqli::real_escape_string
mysqli::real_escape_string
mysqli_real_escape_string
(PHP 5, PHP 7)
mysqli :: real_escape_string - mysqli_real_escape_string - 转义字符串中的特殊字符以便在SQL语句中使用,同时考虑连接的当前字符集
描述
面向对象的风格
string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )
程序风格
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
该函数用于创建可在SQL语句中使用的合法SQL字符串。给定的字符串编码为转义的SQL字符串,并考虑到连接的当前字符集。
警告
安全性:默认字符集
字符集必须设置在服务器级别,或者使用API函数mysqli_set_charset()来影响mysqli_real_escape_string()
。有关更多信息,请参阅字符集的概念部分。
参数
`link`
仅过程样式:由mysqli_connect()或mysqli_init()返回的链接标识符
escapestr
要转义的字符串。
编码的字符是NUL(ASCII 0),\ n,\ r,\,',“和Control-Z
。
返回值
返回一个转义字符串。
错误/异常
如果没有通过有效的MySQLi连接,执行此函数将返回NULL并发出E_WARNING级别错误。
例子
示例#1 mysqli :: real_escape_string()示例
面向对象的风格
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error()
exit(
}
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", $mysqli->sqlstate
}
$city = $mysqli->real_escape_string($city
/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", $mysqli->affected_rows
}
$mysqli->close(
?>
程序风格
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world"
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error()
exit(
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City"
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link)
}
$city = mysqli_real_escape_string($link, $city
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link)
}
mysqli_close($link
?>
上面的例子会输出:
Error: 42000
1 Row inserted.
注意
注意
:对于习惯于使用mysql_real_escape_string()的用户,请注意
mysqli_real_escape_string()
的参数与mysql_real_escape_string()所期望的不同。所述link
标识符至上在mysqli_real_escape_string(),
而进行转义字符串至上在mysql_real_escape_string() 。
扩展内容
- mysqli_set_charset() - 设置默认的客户端字符集
- mysqli_character_set_name() - 返回数据库连接的默认字符集
← mysqli::real_connect
mysqli::real_query →