Vous êtes sur la page 1sur 13

Change language: French

Edit Report a Bug


Search
La classe PDOStatement
(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 1.0.0)

Introduction

Représente une requête préparée et, une fois exécutée, le jeu de résultats associé.

Synopsis de la classe

PDOStatement implements Traversable {

/* Propriétés */
readonly string $queryString;

/* Méthodes */
public bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed
$driverdata ]]] ) : bool
public bindParam ( mixed $parameter , mixed &$variable [, int $data_type =
PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] ) : bool
public bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ]
) : bool
public closeCursor ( void ) : bool
public columnCount ( void ) : int
public debugDumpParams ( void ) : void
public errorCode ( void ) : string
public errorInfo ( void ) : array
public execute ([ array $input_parameters ] ) : bool
public fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [,
int $cursor_offset = 0 ]]] ) : mixed
public fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args =
array() ]]] ) : array
public fetchColumn ([ int $column_number = 0 ] ) : mixed
public fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] ) : mixed
public getAttribute ( int $attribute ) : mixed
public getColumnMeta ( int $column ) : array
public nextRowset ( void ) : bool
public rowCount ( void ) : int
public setAttribute ( int $attribute , mixed $value ) : bool
public setFetchMode ( int $mode ) : bool
}

Propriétés

queryString
chaîne de caractères utilisée pour la requête.

Sommaire

PDOStatement::bindColumn — Lie une colonne à une variable PHP


PDOStatement::bindParam — Lie un paramètre à un nom de variable spécifique
PDOStatement::bindValue — Associe une valeur à un paramètre
PDOStatement::closeCursor — Ferme le curseur, permettant à la requête d'être de nouveau
exécutée
PDOStatement::columnCount — Retourne le nombre de colonnes dans le jeu de résultats
PDOStatement::debugDumpParams — Détaille une commande préparée SQL
PDOStatement::errorCode — Récupère les informations sur l'erreur associée lors de la dernière
opération sur la requête
PDOStatement::errorInfo — Récupère les informations sur l'erreur associée lors de la dernière
opération sur la requête
PDOStatement::execute — Exécute une requête préparée
PDOStatement::fetch — Récupère la ligne suivante d'un jeu de résultats PDO
PDOStatement::fetchAll — Retourne un tableau contenant toutes les lignes du jeu d'enregistrements
PDOStatement::fetchColumn — Retourne une colonne depuis la ligne suivante d'un jeu de résultats
PDOStatement::fetchObject — Récupère la prochaine ligne et la retourne en tant qu'objet
PDOStatement::getAttribute — Récupère un attribut de requête
PDOStatement::getColumnMeta — Retourne les métadonnées pour une colonne d'un jeu de
résultats
PDOStatement::nextRowset — Avance à la prochaine ligne de résultats d'un gestionnaire de lignes
de résultats multiples
PDOStatement::rowCount — Retourne le nombre de lignes affectées par le dernier appel à la
fonction PDOStatement::execute()
PDOStatement::setAttribute — Définit un attribut de requête
PDOStatement::setFetchMode — Définit le mode de récupération par défaut pour cette requête

User Contributed Notes 6 notes add a note

Gino D. 1 year ago


3
I don't know why PDOStatement don't return "execution time" and "found rows" so here
I created an extended class of PDOStatement with these attributes.

Just have to "setAttribute" of PDO's object to $PDO-


>setAttribute(\PDO::ATTR_STATEMENT_CLASS , ['\customs\PDOStatement', [&$this]]);

<?php

/**
*
*
*
*/

namespace customs;

/**
*
*
*
*/

final class PDOStatement extends \PDOStatement {

/**
*
*
*
*/

protected $PDO = null;


protected $inputParams = [];
protected $executionTime = 0;
protected $resultCount = 0;

/**
*
*
*
*/

protected function __construct(PDO &$PDO) {


$this->PDO = $PDO;
$this->executionTime = microtime(true);
}

/**
*
*
*
*/

final public function getExecutionError(int $i = 2) {


$executionError = $this->errorInfo();

if (isset($executionError[$i]))
return $executionError[$i];

return $executionError;
}

/**
*
*
*
*/

final public function getExecutionTime($numberFormat = false, $decPoint = '.',


$thousandsSep = ',') {
if (is_numeric($numberFormat))
return number_format($this->executionTime, $numberFormat, $decPoint,
$thousandsSep);

return $this->executionTime;
}

/**
*
*
*
*/

final public function getResultCount($numberFormat = false, $decPoint = '.',


$thousandsSep = ',') {
if (is_numeric($numberFormat))
return number_format($this->resultCount, $numberFormat, $decPoint,
$thousandsSep);
return $this->resultCount;
}

/**
*
*
*
*/

final public function getLastInsertId() {


return $this->PDO->lastInsertId();
}

/**
*
*
*
*/

final public function bindValues(array $inputParams) {


foreach ($this->inputParams = array_values($inputParams) as $i => $value) {
$varType = is_null($value) ? \PDO::PARAM_NULL : is_bool($value) ?
\PDO::PARAM_BOOL : is_int($value) ? \PDO::PARAM_INT : \PDO::PARAM_STR;

if (!$this->bindValue(++ $i, $value, $varType))


return false;
}

return true;
}

/**
*
*
*
*/

final public function execute($inputParams = null) {


if ($inputParams)
$this->inputParams = $inputParams;

if ($executed = parent::execute($inputParams))
$this->executionTime = microtime(true) - $this->executionTime;
return $executed;
}

/**
*
*
*
*/

final public function fetchAll($how = null, $className = null, $ctorArgs = null) {


$resultSet = parent::fetchAll(... func_get_args());

if (!empty($resultSet)) {
$queryString = $this->queryString;
$inputParams = $this->inputParams;

if (preg_match('/(.*)?LIMIT/is', $queryString, $match))


$queryString = $match[1];

$queryString = sprintf('SELECT COUNT(*) AS T FROM (%s) DT', $queryString);

if (($placeholders = substr_count($queryString, '?')) < count($inputParams))


$inputParams = array_slice($inputParams, 0, $placeholders);

if (($sth = $this->PDO->prepare($queryString)) && $sth-


>bindValues($inputParams) && $sth->execute())
$this->resultCount = $sth->fetchColumn();

$sth = null;
}

return $resultSet;
}
}
?>

1 luis-m-cardoso at ext dot ptinovacao dot pt 5 years ago

Solved ;)

<?php

$host = "yourHost";
$user = "yourUser";
$pass = "yourPass";
$db = "yourDB";

$cursor = "cr_123456";

try
{
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
echo "Connected<p>";
}
catch (Exception $e)
{
echo "Unable to connect: " . $e->getMessage() ."<p>";
}

$dbh->beginTransaction();

$query = "SELECT yourFunction(0::smallint,'2013-08-01 00:00','2013-09-01


00:00',1::smallint,'$cursor')";

$dbh->query($query);

$query = "FETCH ALL IN \"$cursor\"";

echo "begin data<p>";

foreach ($dbh->query($query) as $row)


{
echo "$row[0] $row[1] $row[2] <br>";
}

echo "end data";

?>

-2 Example 10 months ago

1.- Conectar a la base de datos usando try/catch.


$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass");

2.- Preparar la consulta (insert,update,delete).


2.1.- Preparar la consulta:
$stmt = $pdo->prepare("INSERT INTO alumnos( nombre, apellidos) values (
'Taylor','Swift' )");
$stmt = $pdo->prepare("INSERT INTO colegas (name, addr, city) values (?, ?, ?)");
$stmt = $pdo->prepare("INSERT INTO colegas (name, addr, city) value (:name, :addr,
:city)");

2.2.- Asignar parámetros en la consulta:


$stmt->bindParam(':name', $name);
$name='Pepito';

$datos = array('Cathy', '9 Dark and Twisty Road', 'Cardiff');


$stmt = $pdo->prepare("INSERT INTO colegas (name, addr, city) values (?, ?, ?)");

$datos = array( 'name' => 'Cathy', 'addr' => '9 Dark and Twisty', 'city' => 'Cardiff'
);
$stmt = $pdo->prepare("INSERT INTO colegas (name, addr, city) value (:name, :addr,
:city)");

2.3.- Ejecutar la consulta


try{
$stmt->execute();

// o bien
$stmt->execute($datos);
}
catch(PDOException $err)
{
// Mostramos un mensaje genérico de error.
echo "Error: ejecutando consulta SQL.";
}

2.- Preparar la consulta (select).


2.1.- Preparar la consulta:
try{
// ATENCION: si no tenemos parámetros en la consulta, la podemos ejecutar con -
>query (recomendable en SELECT) o con ->exec (para INSERT, UDPATE, DELETE)
$stmt = $pdo->query('SELECT name, addr, city from colegas');
}
catch(PDOException $err)
{
// Mostramos un mensaje genérico de error.
echo "Error: ejecutando consulta SQL.";
}

$stmt = $pdo->prepare('SELECT name, addr, city from colegas where city =:ciudad'); (con
parámetros)
$datos = array( ':ciudad' => 'Santiago');

try{
$stmt->execute($datos);
}
catch(PDOException $err)
{
// Mostramos un mensaje genérico de error.
echo "Error: ejecutando consulta SQL.";
}

2.2.- Leemos los datos del recordset (conjunto de registros) que nos devuelve SELECT en el
objeto PDOStatement.

2.2.1.- Se puede leer cada fila del recordset con ->fetch() del objeto PDOStatement o
mediante ->fetchAll() (obtiene todas las filas del recordset).
'''Este bloque de código lo ejecutaremos dentro de la sección try { ..... }'''

while($row = $stmt->fetch()) {
echo $row['name'] . "<br/>";
echo $row['addr'] . "<br/>";
echo $row['city'] . "<br/>";
}

$row = $sql->fetchAll();
foreach($data as $row)
$id = $row['id'];
$content = $row['content'];
}

3.- Cerrar la conexión.


// Liberamos los recursos utilizados por el recordset $stmt
$stmt=null;

// Se recomienda cerrar la conexión para liberar recursos de forma más rápida.


$pdo = null;

-5 code4fun at gmail dot com 10 months ago

Example of persist in bd

public function persist($dbh) {


if ($this->id) {//Update
$modificar = 'UPDATE usuarios set nombre = :nombre ,pass = :pass'
. ' WHERE id = :id';
$persistir = $dbh->prepare($modificar);
$persistido = $persistir->execute(array(':nombre' => $this->getNombre(),
':pass' => $this->getPass(), ':id' => $this->getId()));
} else {
$insert = 'INSERT INTO usuarios (nombre,pass) VALUES (:nombre,:pass)';
$persistir = $dbh->prepare($insert);
$persistido = $persistir->execute(array('nombre' => $this->getNombre(), 'pass'
=> $this->getPass()));
if ($persistido) {
$this->setId($dbh->lastInsertId());
} else {
throw new Exception;
}
}
return $persistido;
}

//Example of select

public function getCredencial($dbh) {


$select = "SELECT * FROM usuarios WHERE nombre= :user AND pass= :pass";
$consulta = $dbh->prepare($select);
$consulta->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, "Usuario");
$consulta->execute(array(":user" => $this->nombre, ":pass" => $this->pass));
$logueado = $consulta->fetch();
return $logueado;
}

//Example of select all


public static function getAll($bd, $id) {
$query = 'SELECT * FROM `cuentas` WHERE idUsuario = :idUsuario';
$prepare = $bd->prepare($query);
$prepare->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Movimiento');
$prepare->execute(array(':idUsuario' => $id));
$movimientos = $prepare->fetchAll();
return $movimientos;
}

//Example of delete

public function eliminar($dbh,$id) {


$sql = 'DELETE FROM alumnos '
. 'WHERE id = :id';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id', $id);

$stmt->execute();

return $stmt->rowCount();
}

-5 code4fun at gmail dot com 10 months ago

Example of persist in bd

public function persist($dbh) {


if ($this->id) {//Update
$modificar = 'UPDATE usuarios set nombre = :nombre ,pass = :pass'
. ' WHERE id = :id';
$persistir = $dbh->prepare($modificar);
$persistido = $persistir->execute(array(':nombre' => $this->getNombre(),
':pass' => $this->getPass(), ':id' => $this->getId()));
} else {
$insert = 'INSERT INTO usuarios (nombre,pass) VALUES (:nombre,:pass)';
$persistir = $dbh->prepare($insert);
$persistido = $persistir->execute(array('nombre' => $this->getNombre(), 'pass'
=> $this->getPass()));
if ($persistido) {
$this->setId($dbh->lastInsertId());
} else {
throw new Exception;
}
}
return $persistido;
}

//Example of select

public function getCredencial($dbh) {


$select = "SELECT * FROM usuarios WHERE nombre= :user AND pass= :pass";
$consulta = $dbh->prepare($select);
$consulta->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, "Usuario");
$consulta->execute(array(":user" => $this->nombre, ":pass" => $this->pass));
$logueado = $consulta->fetch();
return $logueado;
}
//Example of select all
public static function getAll($bd, $id) {
$query = 'SELECT * FROM `cuentas` WHERE idUsuario = :idUsuario';
$prepare = $bd->prepare($query);
$prepare->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Movimiento');
$prepare->execute(array(':idUsuario' => $id));
$movimientos = $prepare->fetchAll();
return $movimientos;
}

//Example of delete

public function eliminar($dbh,$id) {


$sql = 'DELETE FROM alumnos '
. 'WHERE id = :id';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id', $id);

$stmt->execute();

return $stmt->rowCount();
}

-61 rosko at zeta dot org dot au 9 years ago

There are many references around for returning a refcursor from a pgSQL function using
pg_query. All essentially boil down to executing the following single statement (or some
variation of it):

begin; select yourFunction(params...); fetch all in cursorname; commit;

In PDO, this doesn't work because PDO won't allow multiple statements submitted as a
single statement (due to SQL injection detection). Instead, try this or similar:

<?php
$sql = 'select yourFunction(params...)';
$db = new PDO('pgsql:dbname=yourDBname');
$db->beginTransaction();
$cmd = $db->prepare($sql);
if ($cmd->execute()) {
if ($query = $db->query('fetch all in cursorname')) {
...processing...
$query->closeCursor();
$cmd->closeCursor();
}
}
$db->commit();
?>

add a note

PDO
Introduction
Installation/Configuration
Constantes pré-définies
Connexions et gestionnaire de connexion
Transactions et validation automatique (autocommit)
Requêtes préparées et procédures stockées
Les erreurs et leur gestion
Les gros objets (LOB)
PDO
» PDOStatement
PDOException
Pilotes PDO

Copyright © 2001-2019 The PHP Group My PHP.net Contact Other PHP.net sites

Mirror sites Privacy policy

Vous aimerez peut-être aussi