CakeFest 2024: The Official CakePHP Conference

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::bindValueVincula o valor de um parâmetro a uma variável de instrução

Descrição

public SQLite3Stmt::bindValue(string|int $param, mixed $value, int $type = SQLITE3_TEXT): bool

Vincula o valor de um parâmetro a uma variável de instrução.

Cuidado

Antes do PHP 7.2.14 e 7.3.0, respectivamente, uma vez que a instrução foi executada, SQLite3Stmt::reset() precisa ser chamado para poder alterar o valor dos parâmetros vinculados.

Parâmetros

param

Ou uma string (para parâmetros nomeados) ou um int (para parâmetros posicionais) identificando a variável de instrução à qual o valor deve ser vinculado. Se um parâmetro nomeado não começar com dois pontos (:) ou um sinal de arroba (@), dois pontos (:) são automaticamente adicionados. Parâmetros posicionais começam com 1.

value

O valor a ser vinculado a uma variável de instrução.

type

O tipo de dados do valor a ser vinculado.

  • SQLITE3_INTEGER: O valor é um inteiro assinado, armazenado em 1, 2, 3, 4, 6 ou 8 bytes, dependendo da magnitude do valor.

  • SQLITE3_FLOAT: O valor é um valor de ponto flutuante, armazenado como um número de ponto flutuante IEEE de 8 bytes.

  • SQLITE3_TEXT: O valor é uma string de texto, armazenada usando a codificação do banco de dados (UTF-8, UTF-16BE ou UTF-16-LE).

  • SQLITE3_BLOB: O valor é um blob de dados, armazenado exatamente como foi inserido.

  • SQLITE3_NULL: O valor é um valor NULL.

A partir do PHP 7.0.7, se type for omitido, ele é automaticamente detectado a partir do tipo do value: bool e int são tratados como SQLITE3_INTEGER, float como SQLITE3_FLOAT, null como SQLITE3_NULL e todos os outros como SQLITE3_TEXT. Anteriormente, se type fosse omitido, ele era predefinido como SQLITE3_TEXT.

Nota:

Se value for null, ele é sempre tratado como SQLITE3_NULL, independentemente do type fornecido.

Valor Retornado

Retorna true se o valor for vinculado à variável de instrução, ou false em caso de falha.

Registro de Alterações

Versão Descrição
7.4.0 param agora também suporta a notação @param.

Exemplos

Exemplo #1 Exemplo de SQLite3Stmt::bindValue()

<?php
$db
= new SQLite3(':memory:');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray(SQLITE3_ASSOC));
?>

O exemplo acima produzirá:

array(1) {
  ["bar"]=>
  string(14) "This is a test"
}

Veja Também

add a note

User Contributed Notes 4 notes

up
34
zeebinz at gmail dot com
13 years ago
Note that this also works with positional placeholders using the '?' token:

<?php

$stmt
= $db->prepare('SELECT * FROM mytable WHERE foo = ? AND bar = ?');
$stmt->bindValue(1, 'somestring', SQLITE3_TEXT);
$stmt->bindValue(2, 42, SQLITE3_INTEGER);

?>

Positional numbering starts at 1.
up
11
andrevanzuydam at gmail dot com
8 years ago
I just want to say again,

Numbering for parameters starts at ONE!

This has caught me out quite a few times!
up
1
bohwaz
9 years ago
It might be a good idea to feed bindValue the type of the variable manually, or you might encounter weird stuff as the passed value is often treated as SQLITE3_TEXT and results in buggy queries.

For example:
<?php
$st
= $db->prepare('SELECT * FROM test WHERE (a+1) = ?');
$st->bindValue(1, 2);
?>

Will never return any result as it is treated by SQLite as if the query was 'SELECT * FROM test WHERE (a+1) = "2"'. Instead you have to set the type manually:

<?php
$st
= $db->prepare('SELECT * FROM test WHERE (a+1) = ?');
$st->bindValue(1, 2, \SQLITE3_INTEGER);
?>

And it will work. This bug is reported in https://bugs.php.net/bug.php?id=68849

Here is a simple function to help you make bindValue work correctly:

<?php
function getArgType($arg)
{
switch (
gettype($arg))
{
case
'double': return SQLITE3_FLOAT;
case
'integer': return SQLITE3_INTEGER;
case
'boolean': return SQLITE3_INTEGER;
case
'NULL': return SQLITE3_NULL;
case
'string': return SQLITE3_TEXT;
default:
throw new
\InvalidArgumentException('Argument is of invalid type '.gettype($arg));
}
}
?>
up
0
vaibhavatul47 at gmail dot com
7 years ago
I used following logic to prepare statements, It handles both Values and Arrays ( taking help from bohwaz note) :

<?php
function getArgType($arg) {
switch (
gettype($arg)) {
case
'double': return SQLITE3_FLOAT;
case
'integer': return SQLITE3_INTEGER;
case
'boolean': return SQLITE3_INTEGER;
case
'NULL': return SQLITE3_NULL;
case
'string': return SQLITE3_TEXT;
default:
throw new
\InvalidArgumentException('Argument is of invalid type '.gettype($arg));
}
}

foreach (
$params as $index => $val) {
// indexing start from 1 in Sqlite statement
if (is_array($val)) {
$ok = $stmt->bindParam($index + 1, $val);
} else {
$ok = $stmt->bindValue($index + 1, $val, getArgType($val));
}

if (!
$ok) {
throw new
Exception("Unable to bind param: $val");
}
}
?>
To Top