«

PHP:PDO::quote()方法参数说明

时间:2024-3-1 21:15     作者:韩俊     分类: PHP


PDO::quote

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

PDO::quote — Quotes a string for use in a query.

说明

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

PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Caution Security: the default character set

The character set must be set either on the server level, or within the database connection itself (depending on the driver) for it to affect PDO::quote(). See the driver-specific documentation for more information.

参数

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.


返回值

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

范例


Example #1 Quoting a normal string

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

/* Simple string */
$string = 'Nice';
print "Unquoted string: $stringn";
print "Quoted string: " . $conn->quote($string) . "n";
?>

以上例程会输出:

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 Quoting a dangerous string

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

/* Dangerous string */
$string = 'Naughty ' string';
print "Unquoted string: $stringn";
print "Quoted string:" . $conn->quote($string) . "n";
?>

以上例程会输出:

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

Example #3 Quoting a complex string

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

/* Complex string */
$string = "Co'mpl''ex "st'"ring";
print "Unquoted string: $stringn";
print "Quoted string: " . $conn->quote($string) . "n";
?>

以上例程会输出:

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


参见

PDO::prepare() - Prepares a statement for execution and returns a statement object PDOStatement::execute() - 执行一条预处理语句

标签: php php教程

热门推荐