PDO::quote

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.1)

PDO::quote 为 SQL 查询里的字符串添加引号

说明

public PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] ) : string

PDO::quote() 为输入的字符串添加引号(如果有需要),并对特殊字符进行转义,且引号的风格和底层驱动适配。

如果使用此函数构建 SQL 语句,强烈建议使用 PDO::prepare() 配合参数构建,而不是用 PDO::quote() 把用户输入的数据拼接进 SQL 语句。 使用 prepare 语句处理参数,不仅仅可移植性更好,而且更方便、免疫 SQL 注入;相对于拼接 SQL 更快,客户端和服务器都能缓存编译后的 SQL 查询。

不是所有的 PDO 驱动都实现了此功能(例如 PDO_ODBC)。 考虑使用 prepare 代替。

Caution

安全性:默认字符集

字符集不仅仅要在数据库服务器上设置,也要为数据库连接设置(取决于驱动),它影响了 PDO::quote()。 更多信息可参考PDO 驱动文档

参数

string

要添加引号的字符串。

parameter_type

为驱动提示数据类型,以便选择引号风格。

返回值

返回加引号的字符串,理论上可以安全用于 SQL 语句。 如果驱动不支持这种方式,将返回 FALSE

范例

Example #1 普通字符串加引号

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* 简单字符串 */
$string 'Nice';
print 
"Unquoted string: $string\n";
print 
"Quoted string: " $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 危险字符串加引号

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* 危险字符串 */
$string 'Naughty \' string';
print 
"Unquoted string: $string\n";
print 
"Quoted string:" $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #3 复杂字符串加引号

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* 复杂字符串 */
$string "Co'mpl''ex \"st'\"ring";
print 
"Unquoted string: $string\n";
print 
"Quoted string: " $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

参见

相关文章
php 字符串 函数 转换十六进制字符串为二进制字符串php mysql 函数 转义 sql 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集php mysql 函数 向 mysql 发送一条 sql 查询,并不获取和缓存结果的行php mysqlnd ms 函数 查询给定的 sql 会发送给 master、slave 还是最后使用的 mysql server 执行。php 4d pdo sql types with pdo 4d and phpphp pdo 执行一条 sql 语句,并返回受影响的行数php pdo 执行 sql 语句,以 pdostatement 对象形式返回结果集php pdo 为 sql 查询里的字符串添加引号php sqlite pdo registers an aggregating user defined function for use in sql statementsphp sqlite pdo registers a user defined function for use as a collating function in sql statementsphp sqlite pdo registers a user defined function for use in sql statementsphp phar 以字符串的形式添加一个文件到 phar 档案php 4d pdo connecting to 4d sql serverphp 4d pdo pdo and sql 4dphp ms sql server pdo connecting to microsoft sql server and sybase databasesphp pdo 驱动 microsoft sql server and sybase functions pdo dblib php ms sql server pdo connecting to ms sql server and sql azure databasesphp pdo 驱动 microsoft sql server functions pdo sqlsrv php reflectionmethod 返回反射方法对象的字符串表达php sdo das relational 函数 executes an sql query passed as a prepared statement with a list of values to substitute for placeholders and return the results as a normalised data graph
关注编程学问公众号