PHP.mk документација

PDOStatement::bindValue

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

pdostatement.bindvalue.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека pdostatement.bindvalue.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
PDOStatement::bindValue

Референца за `pdostatement.bindvalue.php` со подобрена типографија и навигација.

pdostatement.bindvalue.php

PDOStatement::bindValue

PDOStatement класа

PDOStatement::bindValue Врзува вредност за параметар

= NULL

public PDOStatement::bindValue(string|int $param, mixed $value, int $type = PDO::PARAM_STR): bool

Врзува вредност за соодветниот именуван или прашалник во SQL изјавата што се користеше за подготовка на изјавата.

Параметри

param

Идентификатор на параметар. За подготвена изјава што користи именувани заменски знаци, ова ќе биде име на параметар од форма :name. За подготвена изјава што користи заменски знаци со прашалник, ова ќе биде позицијата на параметарот со индекс 1.

value

Вредноста што треба да се врзе за параметарот.

type

Експлицитен тип на податоци за параметарот користејќи го PDO::PARAM_* constants.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Errors/Exceptions

Емитува грешка со ниво E_WARNING ако атрибутот PDO::ATTR_ERRMODE е поставен на PDO::ERRMODE_WARNING.

Фрла PDOException ако атрибутот PDO::ATTR_ERRMODE е поставен на PDO::ERRMODE_EXCEPTION.

Примери

Пример #1 Изврши подготвена изјава со именувани заменски знаци

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour'
);

/* Sets a parameter value using its name */
$sth->bindValue('calories', $calories, PDO::PARAM_INT);
/* Optionally, parameter names can also be prefixed with colons ":" */
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Пример #2 Изврши подготвена изјава со заменски знаци со прашалник

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?'
);
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

Види Исто така

Белешки од корисници 11 белешки

streaky at mybrokenlogic dot com
пред 18 години
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.
D.Kellner
пред 10 години
When binding parameters, apparently you can't use a placeholder twice (e.g. "select * from mails where sender=:me or recipient=:me"), you'll have to give them different names otherwise your query will return empty handed (but not fail, unfortunately).  Just in case you're struggling with something like this.
e-ruiz at git hub
пред 9 години
Be careful when trying to validate using PDO::PARAM_INT. 

Take this sample into account:

<?php
/* php --version
 * PHP 5.6.25 (cli) (built: Aug 24 2016 09:50:46)
 * Copyright (c) 1997-2016 The PHP Group
 * Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
 */

$id = '1a'; 
$stm = $pdo->prepare('select * from author where id = :id');
$bind = $stm->bindValue(':id', $id, PDO::PARAM_INT);

$stm->execute();
$authors = $stm->fetchAll();

var_dump($id);         // string(2)
var_dump($bind);       // true
var_dump((int)$id);    // int(1)
var_dump(is_int($id)); // false
var_dump($authors);    // the author id=1  =(

// remember
var_dump(1 == '1');    // true
var_dump(1 === '1');   // false
var_dump(1 === '1a');  // false
var_dump(1 == '1a');   // true
?>

My opinion: bindValue() should test is_int() internaly first of anything, 
It is a bug? I'm not sure.
cpd-dev
пред 16 години
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.
Анонимен
пред 14 години
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

?>
contact[at]maximeelomari.com
пред 14 години
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.
 * */
?>
Владимир Ковпак
пред 11 години
<?php
/**
* Bind bit value.
*/

$sql = 'SELECT * FROM myTable WHERE level & ?';
$sth = \App::pdo()->prepare($sql);
$sth->bindValue(1, 0b0101, \PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
me at iabdullah dot info
пред 11 години
The reason that we cannot define the value variable for bindValue() after calling it, is because that it binds the value to the prepared statement immediately and does not wait until the execute() to happen.

The following code will issue a notice and prevent the query from taking place:
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id= :val ");
    $st->bindValue(':val',$val);

    $val = '2';
    $st->execute();
?>
The output:
Notice: Undefined variable: val.

Whereas in the case of bindParam, the evaluation of the value to the parameter will not be performed until the call of execute(). And that's to gain the benefit of reference passing.
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id = :val ");
    $st->bindParam(':val',$val);

    $val = '2';
    // 
    // some code
    //
    $val = '3'; // re-assigning the value variable
    $st->execute();
?>
works fine.
nicolas dot baptiste at gmail dot com
пред 16 години
This actually works to bind NULL on an integer field in MySQL :

$stm->bindValue(':param', null, PDO::PARAM_INT);
sageptr на gmail точка com
пред 9 години
Be careful in edge cases!
With MySQL native prepares your integer can be wrapped around on some machines:

<?php
$x = 2147483648;
var_dump($x); // prints: int(2147483648)
$s = $db->prepare('SELECT :int AS I, :str AS S;');
$s->bindValue(':int', $x, PDO::PARAM_INT);
$s->bindValue(':str', $x, PDO::PARAM_STR);
$s->execute();
var_dump( $s->fetchAll(PDO::FETCH_ASSOC) );
/* prints: array(2) {
  ["I"]=>
  string(11) "-2147483648"
  ["S"]=>
  string(10) "2147483648"
} */
?>

Also, trying to bind PDO::PARAM_BOOL in MySQL with native prepares can make your query silently fail and return empty set.

Emulated prepares work more stable in this cases, because they convert everything to strings and just decide whenever to quote argument or not to quote.
goofiq dot no dot spam at antispam dot wp dot pl
пред 16 години
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 ();
  }

}

?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.