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 Entrecomilla una cadena de caracteres para usarla en una consulta

Descripción

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

PDO::quote() entrecomilla el string de entrada (si fuera necesario) y escapa los caracteres especiales contenidos en dicho string, usando un estilo de entrecomillado apropiado para el controlador subyacente.

Si se usa esta función para construir sentencias SQL, se recomienda encarecidamente usar PDO::prepare() para preparar sentencias SQL con los parámetros vinculados en vez de usar PDO::quote() para interpolar entradas del usuario en una consulta SQL. Las sentencias preparadas con parámetros vinculados no son sólo más portables, más convenientes, e inmunes a inyecciones SQL, sino que son mucho más rápidas de ejecutar que las consultas interpoladas, ya que tanto el lado del servidor como el del cliente pueden almacenar en caché una forma compilada de la consulta.

No todos los controladores de PDO implementan este método (como ejemplo notable, PDO_ODBC). En su lugar, se ha de considerar el uso de sentencias preparadas.

Precaución

Seguridad: el conjunto de caracteres predeterminado

El conjunto de caracteres debe establecerse o bien al nivel del servidor, o dentro de la misma conexión a la base de datos (dependiendo del controlador) para que afecte a PDO::quote(). Véase la documentación específica del controlador para más información.

Parámetros

string

La cadena de caracteres a entrecomillar.

parameter_type

Proporciona una sugerencia del tipo de datos para los controladores que tengan un estilo de entrecomillado alternativo.

Valores devueltos

Devuelve un string entrecomillado teóricamente seguro para pasarlo a una sentencia SQL. Devuelve FALSE si el controlador no soporta el entrecomillado en esta forma.

Ejemplos

Ejemplo #1 Entrecomillar una cadena de caracteres normal

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

/* Cadena simple */
$cadena 'Agradable';
print 
"Cadena sin entrecomillar: $cadena\n";
print 
"Cadena entrecomillada: " $conexión->quote($cadena) . "\n";
?>

El resultado del ejemplo sería:

Cadena sin entrecomillar: Agradable
Cadena entrecomillada: 'Agradable'

Ejemplo #2 Entrecomillar una cadena peligrosa

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

/* Cadena peligrosa */
$cadena 'Cadena \' desagradable';
print 
"Cadena sin entrecomillar: $cadena\n";
print 
"Cadena entrecomillada:" $conexión->quote($cadena) . "\n";
?>

El resultado del ejemplo sería:

Cadena sin entrecomillar: Cadena ' desagradable
Cadena entrecomillada: 'Cadena '' desagradable'

Ejemplo #3 Entrecomillar una cadena compleja

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

/* Cadena compleja */
$cadena "Ca'de''na \"co'\"mpleja";
print 
"Cadena sin entrecomillar: $cadena\n";
print 
"Cadena entrecomillada: " $conexión->quote($cadena) . "\n";
?>

El resultado del ejemplo sería:

Cadena sin entrecomillar: Ca'de''na "co'"mpleja
Cadena entrecomillada: 'Ca''de''''na "co''"mpleja'

Ver también



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
9 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
4 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
5 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 | sitemap | contact | advertising | mirror sites