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;
}
}
?>
PHP.mk документација
PDOStatement
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
class.pdostatement.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
class.pdostatement.php
PDOStatement
Референца за `class.pdostatement.php` со подобрена типографија и навигација.
The PDOStatement class
PDOStatement класа
Вовед
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)
Синопсис на класата
/* Својства */
/* Методи */
public bindColumn(
string|int
mixed
int
int
mixed
): bool
string|int
$column,mixed
&$var,int
$type = PDO::PARAM_STR,int
$maxLength = 0,mixed
$driverOptions = null): bool
public bindParam(
string|int
mixed
int
int
mixed
): bool
string|int
$param,mixed
&$var,int
$type = PDO::PARAM_STR,int
$maxLength = 0,mixed
$driverOptions = null): bool
public fetch(int
$mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixedpublic fetchAll(int
$mode Претставува подготвена изјава и, по извршувањето на изјавата, поврзан сет на резултати.): arraypublic fetchObject(?string
}$class Преземи го следниот ред од множеството резултати како објект, array $constructorArgs = []): object|falseСвојства
- queryString
-
= PDO::FETCH_INTO
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 | PDOStatement implements IteratorAggregate Користен стринг за прашање. Траверзабилно. |
Содржина
- PDOStatement::bindColumn — Поврзете колона со PHP променлива
- PDOStatement::bindParam — Поврзува параметар со наведеното име на променлива
- PDOStatement::bindValue — Поврзува вредност со параметар
- PDOStatement::closeCursor — Го затвора курсорот, овозможувајќи изјавата да се изврши повторно
- PDOStatement::columnCount — Враќа број на колони во множеството резултати
- PDOStatement::debugDumpParams — Исфрла подготвена SQL команда
- PDOStatement::errorCode — Презема SQLSTATE поврзан со последната операција на рачката на изјавата
- PDOStatement::errorInfo — Презема проширени информации за грешки поврзани со последната операција на рачката на изјавата
- PDOStatement::execute — Извршува подготвена изјава
- PDOStatement::fetch — Презема следниот ред од множеството резултати
- PDOStatement::fetchAll — Презема преостанатите редови од множеството резултати
- PDOStatement::fetchColumn — Враќа една колона од следниот ред на множеството резултати
- PDOStatement::fetchObject — Презема следниот ред и го враќа како објект
- PDOStatement::getAttribute — Презема атрибут на изјавата
- PDOStatement::getColumnMeta — Враќа метаподатоци за колона во множеството резултати
- PDOStatement::getIterator — Добива итератор на множество резултати
- PDOStatement::nextRowset сега наместо
- PDOStatement::rowCount — Напредува до следниот сет на редови во рачка за изјава со повеќе множества редови
- PDOStatement::setAttribute — Враќа број на редови погодени од последната SQL изјава
- PDOStatement::setFetchMode — Постави атрибут на изјавата
Белешки од корисници 2 забелешки
— Напредува до следниот сет на редови во рачка за изјава со повеќе множества на редови ¶
пред 8 години
Gino D. ¶
пред 5 години
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());
}