downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

PDO::rollBack> <PDO::query
[edit] Last updated: Fri, 17 May 2013

view this page in

PDO::quote

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

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

Description

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.

Parameters

string

The string to be quoted.

parameter_type

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

Return Values

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.

Examples

Example #1 Quoting a normal string

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

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

The above example will output:

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: $string\n";
print 
"Quoted string:" $conn->quote($string) . "\n";
?>

The above example will output:

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: $string\n";
print 
"Quoted string: " $conn->quote($string) . "\n";
?>

The above example will output:

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

See Also



PDO::rollBack> <PDO::query
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes PDO::quote - [5 notes]
up
3
col dot shrapnel at gmail dot com
14 days ago
OMG, why a note from nemozny at gmail dot com is still here? HOW MANY INJECTIONS it made possible?

Removing quotes from PDO::qiuote IS A DISASTER! Do not use that stupid substr() solution - it will actually open your query to injection.
up
-1
nemozny at gmail dot com
11 months ago
While rewriting some application to PDO, remember that PDO->quote is adding the quotes around the whole value! Compared to mysql_real_escape_string which is quoting only the dangerous characters.

<?php
$value
= "hello's world";
echo
mysql_real_escape_string($value);
// hello''s world

echo $dbh->quote($value);
// 'hello''s world'

// This second quoting will break your old SQL statements which includes the quotes already. Workaround is to remove first and last character

echo substr($dbh->quote($value), 1, -1);
// hello''s world
?>
up
-1
php at deobald dot org
5 years ago
Note that this function just does what the documentation says: It escapes special characters in strings.

It does NOT - however - detect a "NULL" value. If the value you try to quote is "NULL" it will return the same value as when you process an empty string (-> ''), not the text "NULL".
up
0
col dot shrapnel at gmail dot com
10 days ago
One have to understand that string formatting has nothing to do with identifiers.
And thus string formatting should NEVER ever be used to format an identifier ( table of field name).
To quote an identifier, you have to format it as identifier, not as string.
To do so you have to

- Enclose identifier in backticks.
- Escape backticks inside by doubling them.

So, the code would be:
<?php
function quoteIdent($field) {
    return
"`".str_replace("`","``",$field)."`";
}
?>
this will make your identifier properly formatted and thus invulnerable to injection.

However, there is another possible attack vector - using dynamical identifiers in the query may give an outsider control over fields the aren't allowed to:
Say, a field user_role in the users table and a dynamically built INSERT query based on a $_POST array may allow a privilege escalation with easily forged $_POST array.
Or a select query which let a user to choose fields to display may reveal some sensitive information to attacker.

To prevent this kind of attack yet keep queries dynamic, one ought to use WHITELISTING approach.

Every dynamical identifier have to be checked against a hardcoded whitelist like this:
<?php
$allowed 
= array("name","price","qty");
$key = array_search($_GET['field'], $allowed));
if (
$key == false) {
    throw new
Exception('Wrong field name');
}
$field = $db->quoteIdent($allowed[$key]);
$query = "SELECT $field FROM t"; //value is safe
?>
(Personally I wouldn't use a query like this, but that's just an example of using a dynamical identifier in the query).

And similar approach have to be used when filtering dynamical arrays for insert and update:

<?php
function filterArray($input,$allowed)
{
    foreach(
array_keys($input) as $key )
    {
        if ( !
in_array($key,$allowed) )
        {
             unset(
$input[$key]);
        }
    }
    return
$input;
}
//used like this
$allowed = array('title','url','body','rating','term','type');
$data = $db->filterArray($_POST,$allowed);
// $data now contains allowed fields only
// and can be used to create INSERT or UPDATE query dynamically
?>
up
-2
hungry dot rahly at gmail dot com
2 years ago
For those of you who do want to have null returned as NULL, it is fairly easy to add.

<?php
class Real_PDO extends PDO {
  public function
quote($value, $parameter_type = PDO::PARAM_STR ) {
    if(
is_null($value) ) {
      return
"NULL";
    }
    return
parent::quote($value, $parameter_type);
  }
}
?>

then all you have to do is change your creation of the PDO object to this new class, and you shouldn't have to change any other function calls.  The nice thing about this method is that you can override any PDO function or add your own.  IMO, PDO should natively handle this, as there is a difference in databases between NULL and an empty string(''), the quoting of numeric values is another issue altogether.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites