PDOStatement::bindValue

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

PDOStatement::bindValue Vincula un valor a un parámetro

Descripción

public bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )

Vincula un valor al parámetro de sustitución con nombre o de signo de interrogación de la sentencia SQL que se utilizó para preparar la sentencia.

Parámetros

parameter

El identificador del parámetro. Para sentencias preparadas que usen parámetros de sustición con nombre, esto será un nombre de parámetro con la forma :nombre. Para sentencias preparadas que usen parámetros de sustición de signos de interrogación, esto será la posición índice-1 del parámetro.

value

El valor a vincular al parámetro.

data_type

El tipo de datos explícito para el parámetro, usando las constantes PDO::PARAM_*.

Valores devueltos

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Ejemplos

Ejemplo #1 Ejecutar una sentencia preparada con parámetros de sustitución con nombre

<?php
/* Ejecutar una sentencia preparada vinculando varialbes de PHP */
$calorías 150;
$color 'red';
$gsent $gbd->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour'
);
$gsent->bindValue(':calories'$caloríasPDO::PARAM_INT);
$gsent->bindValue(':colour'$colorPDO::PARAM_STR);
$gsent->execute();
?>

Ejemplo #2 Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación

<?php
/* Ejecutar una sentencia preparada vinculando varialbes de PHP */
$calorías 150;
$color 'red';
$gsent $gbd->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?'
);
$gsent->bindValue(1$caloríasPDO::PARAM_INT);
$gsent->bindValue(2$colorPDO::PARAM_STR);
$gsent->execute();
?>

Ver también

add a note add a note

User Contributed Notes 9 notes

up
21
streaky at mybrokenlogic dot com
6 years ago
What the bindValue() docs fail to explain without reading them _very_ carefully is that bindParam() is passed to PDO byref - whereas bindValue() isn't.

Thus with bindValue() you can do something like $stmt->bindValue(":something", "bind this"); whereas with bindParam() it will fail because you can't pass a string by reference, for example.
up
9
cpd-dev
4 years ago
Although bindValue() escapes quotes it does not escape "%" and "_", so be careful when using LIKE. A malicious parameter full of %%% can dump your entire database if you don't escape the parameter yourself. PDO does not provide any other escape method to handle it.
up
4
contact[at]maximeelomari.com
2 years ago
This function is useful for bind value on an array. You can specify the type of the value in advance with $typeArray.

<?php
/**
 * @param string $req : the query on which link the values
 * @param array $array : associative array containing the values ​​to bind
 * @param array $typeArray : associative array with the desired value for its corresponding key in $array
 * */
function bindArrayValue($req, $array, $typeArray = false)
{
    if(
is_object($req) && ($req instanceof PDOStatement))
    {
        foreach(
$array as $key => $value)
        {
            if(
$typeArray)
               
$req->bindValue(":$key",$value,$typeArray[$key]);
            else
            {
                if(
is_int($value))
                   
$param = PDO::PARAM_INT;
                elseif(
is_bool($value))
                   
$param = PDO::PARAM_BOOL;
                elseif(
is_null($value))
                   
$param = PDO::PARAM_NULL;
                elseif(
is_string($value))
                   
$param = PDO::PARAM_STR;
                else
                   
$param = FALSE;
                   
                if(
$param)
                   
$req->bindValue(":$key",$value,$param);
            }
        }
    }
}

/**
 * ## EXEMPLE ##
 * $array = array('language' => 'php','lines' => 254, 'publish' => true);
 * $typeArray = array('language' => PDO::PARAM_STR,'lines' => PDO::PARAM_INT,'publish' => PDO::PARAM_BOOL);
 * $req = 'SELECT * FROM code WHERE language = :language AND lines = :lines AND publish = :publish';
 * You can bind $array like that :
 * bindArrayValue($array,$req,$typeArray);
 * The function is more useful when you use limit clause because they need an integer.
 * */
?>
up
2
nicolas dot baptiste at gmail dot com
4 years ago
This actually works to bind NULL on an integer field in MySQL :

$stm->bindValue(':param', null, PDO::PARAM_INT);
up
0
Anonymous
2 years ago
Note that the third parameter ($data_type) in the majority of cases will not type cast the value into anything else to be used in the query, nor will it throw any sort of error if the type does not match up with the value provided. This parameter essentially has no effect whatsoever except throwing an error if it is set and is not a float, so do not think that it is adding any extra level of security to the queries.

The two exceptions where type casting is performed:

- if you use PDO::PDO_PARAM_INT and provide a boolean, it will be converted to a long
- if you use PDO::PDO_PARAM_BOOL and provide a long, it will be converted to a boolean

<?php

$query
= 'SELECT * FROM `users` WHERE username = :username AND `password` = ENCRYPT( :password, `crypt_password`)';

$sth= $dbh->prepare($query);

// First try passing a random numerical value as the third parameter
var_dump($sth->bindValue(':username','bob', 12345.67)); // bool(true)

// Next try passing a string using the boolean type
var_dump($sth->bindValue(':password','topsecret_pw', PDO::PARAM_BOOL)); // bool(true)

$sth->execute(); // Query is executed successfully
$result = $sth->fetchAll(); // Returns the result of the query

?>
up
0
goofiq dot no dot spam at antispam dot wp dot pl
4 years ago
bindValue with data_type depend parameter name

<?php

$db
= new PDO (...);
$db -> setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('MY_PDOStatement ', array ($db)));

class
MY_PDOStatement extends PDOStatement {

  public function
execute ($input = array ()) {
    foreach (
$input as $param => $value) {
      if (
preg_match ('/_id$/', $param))
       
$this -> bindValue ($param, $value, PDO::PARAM_INT);
      else
       
$this -> bindValue ($param, $value, PDO::PARAM_STR);
    }
    return
parent::execute ();
  }

}

?>
up
0
Anonymous
5 years ago
PDO lacks methods to check if values can be bound to a parameter, e.g.,

if ($statement->hasParameter(':param'))
{
    $statement->bindValue(':param', $value);
}

ATM you *have to know* which parameters exist in the SQL-statement. Otherwise you get an error. You cannot test for them.
up
-1
ts//tpdada//art//pl
7 years ago
For bind whole array at once

<?php

function PDOBindArray(&$poStatement, &$paArray){
 
  foreach (
$paArray as $k=>$v){

    @
$poStatement->bindValue(':'.$k,$v);

  }
// foreach
 
 
} // function

// example

$stmt = $dbh->prepare("INSERT INTO tExample (id,value) VALUES (:id,:value)");

$taValues = array(
 
'id' => '1',
 
'value' => '2'
); // array

PDOBindArray($stmt,$taValues);

$stmt->execute();

?>
up
-2
Lambdaman
4 years ago
If you want to bind a null value to a database field you must use 'NULL' in quotes (for MySQL):

<?php

$stmt
->bindValue(:fieldName, 'NULL');

// not
$stmt->bindValue(:fieldName, NULL);
// or
$stmt->bindValue(:fieldName, null);

?>

Using PHP's null/NULL as a value doesn't work.
To Top