PHP 8.4.22 Released!

The PDOStatement class

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

Introduction

Represents a prepared statement and, after the statement is executed, an associated result set.

Class synopsis

class PDOStatement implements IteratorAggregate {
/* Properties */
/* Methods */
public function bindColumn (
string |int $column,
mixed &$var,
int $type = PDO::PARAM_STR ,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public function bindParam (
string |int $param,
mixed &$var,
int $type = PDO::PARAM_STR ,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public function bindValue (string |int $param, mixed $value, int $type = PDO::PARAM_STR ): bool
public function closeCursor (): bool
public function columnCount (): int
public function debugDumpParams (): ? bool
public function errorCode (): ? string
public function errorInfo (): array
public function execute (? array $params = null ): bool
public function fetch (int $mode = PDO::FETCH_DEFAULT , int $cursorOrientation = PDO::FETCH_ORI_NEXT , int $cursorOffset = 0): mixed
public function fetchAll (int $mode = PDO::FETCH_DEFAULT): array
public function fetchAll (int $mode = PDO::FETCH_COLUMN, int $column): array
public function fetchAll (int $mode = PDO::FETCH_CLASS, string $class, ? array $constructorArgs): array
public function fetchAll (int $mode = PDO::FETCH_FUNC, callable $callback): array
public function fetchColumn (int $column = 0): mixed
public function fetchObject (? string $class = "stdClass", array $constructorArgs = []): object |false
public function getAttribute (int $name): mixed
public function getColumnMeta (int $column): array |false
public function getIterator (): Iterator
public function nextRowset (): bool
public function rowCount (): int
public function setAttribute (int $attribute, mixed $value): bool
public function setFetchMode (int $mode): true
public function setFetchMode (int $mode = PDO::FETCH_COLUMN, int $colno): true
public function setFetchMode (int $mode = PDO::FETCH_CLASS, string $class, ? array $constructorArgs = null ): true
public function setFetchMode (int $mode = PDO::FETCH_INTO, object $object): true
}

Properties

queryString

Used query string.

Changelog

Version Description
8.0.0 PDOStatement implements IteratorAggregate now instead of Traversable .

Table of Contents

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 6 notes

up
17
Gino D.
8 years ago
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;
 }
}
?>
up
0
celest dot noir dot official at gmail dot com
6 days ago
public static function show(int $id): Championship {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT * FROM championships WHERE id = :id';
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 $rowOne = $stmt->fetch(PDO::FETCH_ASSOC);
 if ($rowOne === false) {
 throw new ChampionshipException('Championship not found');
 }
 return Championship::createChampionshipFromArray($rowOne);
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function teamsByChampionship(int $id): array {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT t.* FROM teams t JOIN championship_teams ct ON t.id = ct.team_id WHERE ct.championship_id = :id';
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 if ($rows === false) {
 throw new ChampionshipException('Championship not found');
 }
 $teams = [];
 foreach ($rows as $row) {
 $teams[] = Team::createFromArray($row);
 }
 return $teams;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function deleteChampionship(int $id): bool {
 $sql = 'DELETE FROM championships WHERE id = :id';
 try {
 $connection = Database::getConnection();
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 return $stmt->rowCount() > 0;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
up
0
celest dot noir dot official at gmail dot com
7 days ago
<?php
declare(strict_types=1);
namespace App\Models;
use App\Classes\Championship;
use App\Classes\Team;
use App\Models\Database;
use App\Exceptions\ChampionshipException;
use PDO;
use PDOException;
class ChampionshipModel
{
 public static function store(Championship $championship): bool {
 $dateObject = $championship->getDate();
 $dateString = $dateObject->format('Y-m-d');
 $totalPrize = $championship->getTotalPrize();
 $name = $championship->getName();
 try {
 $connection = Database::getConnection();
 $sql = "INSERT INTO championships (name, date, total_prize) values (:name, :date, :total_prize)";
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':name', $name);
 $stmt->bindValue(':date', $dateString);
 $stmt->bindValue(':total_prize', $totalPrize);
 $stmt->execute();
 return $stmt->rowCount() > 0;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function index(): array {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT * FROM championships';
 $stmt = $connection->prepare($sql);
 $stmt->execute();
 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 $championshipArr = [];
 foreach ($rows as $row) {
 $championshipArr[] = Championship::createChampionshipFromArray($row);
 }
 return $championshipArr;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function show(int $id): Championship {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT * FROM championships WHERE id = :id';
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 $rowOne = $stmt->fetch(PDO::FETCH_ASSOC);
 if ($rowOne === false) {
 throw new ChampionshipException('Championship not found');
 }
 return Championship::createChampionshipFromArray($rowOne);
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function teamsByChampionship(int $id): array {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT t.* FROM teams t JOIN championship_teams ct ON t.id = ct.team_id WHERE ct.championship_id = :id';
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 if ($rows === false) {
 throw new ChampionshipException('Championship not found');
 }
 $teams = [];
 foreach ($rows as $row) {
 $teams[] = Team::createFromArray($row);
 }
 return $teams;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function deleteChampionship(int $id): bool {
 $sql = 'DELETE FROM championships WHERE id = :id';
 try {
 $connection = Database::getConnection();
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':id', $id);
 $stmt->execute();
 return $stmt->rowCount() > 0;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
}
up
0
celest dot noir dot official at gmail dot com
10 days ago
Classic example of simplify consult using PDOStatement with fetch and bind. 
<?php
declare(strict_types=1);
namespace App\Models;
use App\Classes\Championship;
use PDO;
use PDOException;
class ChampionshipModel
{
 public static function store(Championship $championship): bool {
 $dateObject = $championship->getDate();
 $dateString = $dateObject->format('Y-m-d');
 $totalPrize = $championship->getTotalPrize();
 $name = $championship->getName();
 try {
 $connection = Database::getConnection();
 $sql = "INSERT INTO championships(name, date, total_prize) values (:name, :date, :total_prize)";
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':name', $name);
 $stmt->bindValue(':date', $dateString);
 $stmt->bindValue(':total_prize', $totalPrize);
 $stmt->execute();
 return $stmt->rowCount() > 0;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function index(): array {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT * FROM championships';
 $stmt = $connection->prepare($sql);
 $stmt->execute();
 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 $championshipArr = [];
 foreach ($rows as $row) {
 $championshipArr[] = Championship::createChampionshipFromArray($row);
 }
 return $championshipArr;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
}
up
0
nmurzin at mail dot ru
5 years ago
I think I found a way to execute a protected SQL query and at the same time find out the number of affected records.
I have the table 'tbl_users' with the following fields: id, login, password, age
<?
const DB_DRIVER = "mysql";
const DB_HOST = "localhost";
const DB_NAME = "my_db_name";
const DB_LOGIN = "root";
const DB_PASS = "root"; //OpenServer.
$connectionString = DB_DRIVER.':host='.DB_HOST.';dbname='.DB_NAME;
try
{
 //Connect to database.
 $db = new PDO($connectionString, DB_LOGIN, DB_PASS);
}
catch(PDOException $e)
{
 die("Error: ".$e->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
 
 //Decreasing age for user 'nick1'.
 $prep1 = $db->prepare("UPDATE tbl_users SET age=age-1 WHERE login='nick1'");
 //Increasing age for user 'nick2'.
 $prep2 = $db->prepare("UPDATE tbl_users SET \r\n age=age+1 WHERE login='nick2'");
 //Start transaction.
 $db->beginTransaction(); //Table type must be InnerDB!
 //We assume that everything will be fine.
 $flagDone = true; 
 //The exec() method returns the number of rows affected by the query.
 //$prep1->queryString is already an escaped SQL string.
 $result = $db->exec($prep1->queryString);
 if($result==false || $result!=1) //var_dump($result) - int(1) or bool(false).
 $flagDone = false;
 $result = $db->exec($prep2->queryString);
 if($result==false || $result!=1)
 $flagDone = false;
 if($flagDone)
 {
 if($db->commit())
 echo "Transaction was successful";
 } 
 else{
 echo "Transaction fail";
 $db->rollback();
 }
 echo "<br>";
}
catch(PDOException $e)
{
 die("Error: ".$e->getMessage());
}
up
-1
celest dot noir dot official at gmail dot com
10 days ago
Classic example of simplify consult using PDOStatement with fetch and bind. 
<?php
declare(strict_types=1);
namespace App\Models;
use App\Classes\Championship;
use PDO;
use PDOException;
class ChampionshipModel
{
 public static function store(Championship $championship): bool {
 $dateObject = $championship->getDate();
 $dateString = $dateObject->format('Y-m-d');
 $totalPrize = $championship->getTotalPrize();
 $name = $championship->getName();
 try {
 $connection = Database::getConnection();
 $sql = "INSERT INTO championships(name, date, total_prize) values (:name, :date, :total_prize)";
 $stmt = $connection->prepare($sql);
 $stmt->bindValue(':name', $name);
 $stmt->bindValue(':date', $dateString);
 $stmt->bindValue(':total_prize', $totalPrize);
 $stmt->execute();
 return $stmt->rowCount() > 0;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
 public static function index(): array {
 try {
 $connection = Database::getConnection();
 $sql = 'SELECT * FROM championships';
 $stmt = $connection->prepare($sql);
 $stmt->execute();
 $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
 $championshipArr = [];
 foreach ($rows as $row) {
 $championshipArr[] = Championship::createChampionshipFromArray($row);
 }
 return $championshipArr;
 } catch (PDOException $e) {
 throw new PDOException($e->getMessage());
 }
 }
}
+add a note

AltStyle によって変換されたページ (->オリジナル) /