PHP 8.5.0 Alpha 1 available for testing

SQLite3Stmt::bindValue

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

SQLite3Stmt::bindValueAsocia el valor de un parámetro a una variable de declaración

Descripción

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

Asocia el valor de un parámetro a una variable de declaración.

Precaución

Antes de PHP 7.2.14 y 7.3.0, respectivamente, una vez que la declaración ha sido ejecutada SQLite3Stmt::reset() debe ser llamado para poder cambiar el valor de los parámetros asociados.

Parámetros

param

Puede ser un chaîne de caractères (para parámetros nombrados) o un entier (para parámetros posicionales) que identifica la variable de declaración a la cual el valor debe ser asociado. Si un parámetro nombrado no comienza con un carácter "dos puntos" (:) o un arroba (@), "dos puntos" (:) serán automáticamente prefijados. Los parámetros posicionales comienzan con 1.

value

El valor a asociar a la variable de declaración.

type

El tipo de datos del valor a asociar.

  • SQLITE3_INTEGER : El valor es un entero firmado, almacenado en 1, 2, 3, 4, 6, o 8 bytes, según la magnitud del valor.

  • SQLITE3_FLOAT : El valor es un número de punto flotante, almacenado en 8 bytes.

  • SQLITE3_TEXT : El valor es texto, almacenado utilizando la codificación de la base de datos (UTF-8, UTF-16BE o UTF-16-LE).

  • SQLITE3_BLOB : El valor es un BLOB, almacenado exactamente de la forma en que fue proporcionado.

  • SQLITE3_NULL : El valor es la valor NULL.

A partir de PHP 7.0.7, si type es omitido, es automáticamente detectado desde el tipo de value : booléen y entier son tratados como SQLITE3_INTEGER, nombre décimal como SQLITE3_FLOAT, null como SQLITE3_NULL y todos los demás como SQLITE3_TEXT. Anteriormente, si type era omitido, era por omisión SQLITE3_TEXT.

Nota:

Si value es null, siempre fue tratado como SQLITE3_NULL, independientemente del type proporcionado.

Valores devueltos

Retorna true si el valor fue asociado a la variable de declaración, o false en caso de error.

Historial de cambios

Versión Descripción
7.4.0 param ahora soporta la notación @param.

Ejemplos

Ejemplo #1 Ejemplo con 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, 'Ceci est un 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));
?>

El resultado del ejemplo sería:

array(1) {
  ["bar"]=>
  string(16) "Ceci est un test"
}

Ver también

add a note

User Contributed Notes 4 notes

up
34
zeebinz at gmail dot com
14 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
10 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
10 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
-1
vaibhavatul47 at gmail dot com
9 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