Skip to content

Instantly share code, notes, and snippets.

@viccherubini
Created June 12, 2010 15:33
Show Gist options
  • Save viccherubini/435815 to your computer and use it in GitHub Desktop.
Save viccherubini/435815 to your computer and use it in GitHub Desktop.
<?php
declare(encoding='UTF-8');
namespace Adapter;
require_once 'Exception.php';
class Sql {
private $db = NULL;
private $sql = NULL;
private $statement = NULL;
private $statementExecute = NULL;
public function __construct() {
}
public function __destruct() {
}
public function attachDb(\PDO $db) {
$this->db = $db;
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
return $this;
}
public function find($sql, array $input_parameters) {
$this->query($sql, $input_parameters);
$result_set = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
return $result_set;
}
public function getDb() {
return $this->db;
}
public function query($sql, array $input_parameters) {
$this->hasDb();
$this->sql = $sql;
$this->hasSql();
$this->statement = $this->db->prepare($sql);
$this->hasValidPreparedStatement();
$this->statementExecute = $this->statement->execute($input_parameters);
$this->hasValidPreparedStatementExecution();
return $this->statement->rowCount();
}
private function hasDb() {
if ( false === $this->db instanceof \PDO ) {
throw new \Adapter\Exception("Fatal Error: No database attached to object.");
}
return true;
}
private function hasSql() {
if ( true === empty($this->sql) ) {
throw new \Adapter\Exception("Fatal Error: No SQL query present.");
}
return true;
}
private function hasValidPreparedStatement() {
if ( false === $this->statement ) {
$error_info = $this->db->errorInfo();
throw new \Adapter\Exception("An error occurred when preparing {$this->sql}. Driver said {$error_info[2]}.");
}
return true;
}
private function hasValidPreparedStatementExecution() {
if ( false === $this->statementExecute ) {
$error_info = $this->statement->errorInfo();
throw new \Adapter\Exception("An error occurred when executing {$this->sql}. Driver said {$error_info[2]}.");
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment