Files
bsrdb/src/Db/Connection.php
2021-09-27 11:36:32 +02:00

66 lines
1.9 KiB
PHP

<?php
namespace Bsr\Db;
use Bsr\Db\Exception\SqlException;
use Gbili\PDOWithFilters\PDOWithFilters;
class Connection
{
/**
* All params are treated as \PDO::PARAM_STR
* Manually bindParam with a specific \PDO::PARAM_TYPE
* if \PDO::PARAM_STR does not work for you.
* To do it manually copy paste the code below and replace the
* $statement = PDOWithFilters::prepare($sql);
* $success = $statement->execute($values);
* With:
* $statement = PDOWithFilters::prepare($sql);
* $statement->bindParam(':myParam', $values[':myParam'], \PDO::PARAM_TYPE);
* $success = $statement->execute();
*
* @param $query
* @param bool $throw_error
* @return OdbcResultSet|resource|string
* @throws SqlException
*/
public static function execute($sql, $values = array(), $fetchMode = \PDO::FETCH_ASSOC)
{
$statement = PDOWithFilters::prepare($sql);
$success = $statement->execute(!empty($values) ? $values : null);
if (!$success) {
throw new SqlException('SQL There was an error executing the request');
}
if (strpos($sql, "SELECT") !== false || strpos($sql, "OUTPUT INSERTED") !== false) {
$rows = $statement->fetchAll($fetchMode);
if (!is_array($rows)) {
throw new SqlException('PDO Unable to retrieve the result');
}
return new OdbcResultSet($rows);
}
$statement->closeCursor();
return true;
}
/**
* Replaces de old execute($sql, $throwErrors=false)
*
* @param $query
* @return OdbcResultSet|resource|string
*/
public static function executeDontThrow($sql, $values = array(), $fetchMode = \PDO::FETCH_ASSOC)
{
try {
$res = self::execute($sql, $values, $fetchMode);
} catch (SqlException $e) {
$res = false;
}
return $res;
}
private function __clone() {}
}