1 SQL 数据库语句的转义 mysql_real_escape_string
string mysql_real_escape_string ( string unescaped_string [, resource link_identifier] )
本函数将 unescaped_string 中的特殊字符转义,并计及连接的当前字符集,因此可以安全用于 mysql_query()。
注: mysql_real_escape_string() 并不转义 % 和 _。
例子 1. mysql_real_escape_string() 例子
<?php
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
以上例子将产生如下输出:
Escaped string: Zak\'s and Derick\'s Laptop
mysql_escape_string
说明
string mysql_escape_string ( string unescaped_string )
本函数将 unescaped_string 转义,使之可以安全用于 mysql_query()。
注: mysql_escape_string() 并不转义 % 和 _。
本函数和 mysql_real_escape_string() 完全一样,除了 mysql_real_escape_string() 接受的是一个连接句柄并根据当前字符集转移字符串之外。
mysql_escape_string() 并不接受连接参数,也不管当前字符集设定。
addslashes
描述
string addslashes ( string str )返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。
一个使用 addslashes() 的例子是当你要往数据库中输入数据时。例如,将名字 O'reilly 插入到数据库中,这就需要对其进行转义。大多数据库使用 \ 作为转义符:O\'reilly。这样可以将数据放入数据库中,而不会插入额外的 \。当 PHP 指令 magic_quotes_sybase 被设置成 on 时,意味着插入 ' 时将使用 ' 进行转义。
默认情况下,PHP 指令 magic_quotes_gpc 为 on,它主要是对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。
例子 1. addslashes() 示例
<?php
$str = "Is your name O'reilly?";
// 输出:Is your name O\'reilly?
echo addslashes($str);
?>