73 lines
2.0 KiB
PHP
73 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\Common;
|
|
|
|
use PDO,
|
|
PDOStatement;
|
|
|
|
class PdoObject extends PDO {
|
|
|
|
public function select(string $sql, array $parameters = []): PDOStatement
|
|
{
|
|
try {
|
|
if (false !== ( $statement = $this->prepare($sql) )) {
|
|
$statement = $this->execute($statement, $parameters, false);
|
|
$statement->setFetchMode(\PDO::FETCH_ASSOC);
|
|
|
|
return $statement;
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
throw new \PdoException($e->getMessage() . " `$sql` with data:" . json_encode($parameters));
|
|
}
|
|
}
|
|
|
|
public function runQuery(string $sql, array $parameters = []): ? PDOStatement
|
|
{
|
|
try {
|
|
if (false !== ( $statement = $this->prepare($sql) )) {
|
|
return $this->execute($statement, $parameters, true);
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
throw new \PdoException($e->getMessage() . " `$sql` with data:" . json_encode($parameters));
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public function execute(PDOStatement $statement, array $parameters = [], bool $commit = true): ? PDOStatement
|
|
{
|
|
try {
|
|
if ( ! $this->inTransaction() ) {
|
|
$this->beginTransaction();
|
|
}
|
|
|
|
if (empty($parameters) ? $statement->execute() : $statement->execute($parameters)) {
|
|
$statement->lastInsertId = $this->lastInsertId();
|
|
|
|
if ( $commit ) {
|
|
$this->commit();
|
|
}
|
|
|
|
return $statement;
|
|
}
|
|
else {
|
|
throw new \PDOException($statement->errorCode() . " - " . json_encode($statement->errorInfo()));
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
$this->rollback();
|
|
|
|
throw $e;
|
|
}
|
|
catch (\Throwable $e) {
|
|
debogueur($statement, $parameters, $commit);
|
|
|
|
throw $e;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|