<?php
########################################################################
/**
* Classe que extende o objeto PDO
* @author Marcelo Soares da Costa
* @email phpmafia at yahoo dot com dot br
* @copyright Marcelo Soares da Costa © 2007/2009.
* @license FreeBSD http://www.freebsd.org/copyright/freebsd-license.html
* @version 2.0
* @access public
* @changelog
* @package OOE
* @data 2009-06-30
*/
#################################################################################
class ooePDO extends ooeInheritance {
private $objPdo = false;
private $sth;
private $sql;
private $dbh;
private $row;
private $rows;
private $result;
private $affected;
private $queryType;
private $sqlStatment;
private $sqlClean = null;
private $results = array ();
function __construct() {
try{
if (in_array(strtolower(USEDB), PDO::getAvailableDrivers())) {
$this->objPdo=parent :: callClassParent('PDO',strtolower(USEDB) . ":host=" . HOST . ";dbname=" . DATABASE, USER, PASSWORD);
$this->objPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} else {
throw new Exception("Driver " . USEDB . " Unvaliable");
}
} catch (PDOException $e) {
$cathMsg= '<pre>In _autoload set database using for example:
define("USEDB","Mysql"); // Tradicional php mysql driver
or
define("USEDB","pdo.Mysql"); // PDO mysql driver</pre>';
throw new Exception("MSG :".$e->getMessage().$cathMsg);
}
}
/**
*
* Metodo privado para retirar código malicioso
* @access private
* @input SQL {string}
* @return sql {string}
*
*/
private function __sqlClean($sql) {
$arrayInjection = array (
"#",
"--",
"//",
";",
"/*",
"*/",
"drop",
"truncate");
$sqlClean = trim(str_ireplace($arrayInjection, "", $sql));
if ($sqlClean == null) {
throw new Exception("Invalid => SQL:[".$sql."]");
} else {
return $sqlClean;
}
}
#
/**
*
* Metodo privado para verificar o tipo de query
* @access private
* @input SQL {string}
* @return tipo de query {string}
*
*/
private function __queryType($sql) {
unset ($this->queryType);
list ($__queryType) = explode(" ", $sql);
$this->queryType = strtolower($__queryType);
switch ($this->queryType) {
case "select";
return $this->queryType;
break;
case "insert";
return $this->queryType;
break;
case "update";
case "delete";
if (stripos(strtolower($sql), 'where') == true) {
return $this->queryType;
}else{
throw new Exception("Don\'t have clause WHERE in =>SQL:[".$sql."] ");
}
break;
default :
throw new Exception("Invalid => SQL:[".$sql."]");
break;
}
}
/**
*
* Metodo privado que valida a query
* @access private
* @input SQL {string}
* @return exception
*
*/
private function __checkSql($sql) {
try{
$sqlClean=$this->__sqlClean($sql);
$this->__queryType($sqlClean);
return $sqlClean;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
*
* Metodo privado que efetua o prepare
* @access private
* @input SQL {string}
* @return exception
*
*/
private function __prepare($sql) {
unset ($this->sqlPrepare);
try{
$sqlClean=$this->__checkSql($sql);
try{
$this->sth = $this->objPdo->prepare($sqlClean);
$this->sqlPrepare=$sqlClean;
return $this->sqlPrepare;
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :".$e->getMessage());
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
*
* Metodo privado que executa a query
* @access private
* @input SQL {string}
* @return exception
*
*/
private function __execute($param=null) {
unset($this->result);
if($param==null){
try{
$result=$this->sth->execute();
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :".$e->getMessage());
}
}elseif(is_array($param)){
try{
$result=$this->sth->execute($param);
} catch (Exception $e) {
$result=$this->sth->execute(array_values($param));
}
}
}
/**
*
* Metodo publico para envocar o metodo prepare
* @access public
* @input SQL {string}
* @return exception
*
*/
final public function prepareSQL($sql) {
try{
self::__prepare($sql);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
*
* Metodo publico para executar um Statment
* @access public
* @input Statment {array}
* @return result
*
*/
final public function execStatment($param) {
if($this->sqlPrepare!=null)
{
if(is_array($param)){
$array=$param;
}else{
$array=explode(',', $param);
}
$result= self :: __setSql($this->sqlPrepare,$array);
if ($this->queryType == "select") {
return self :: getAssocArray();
} else{
return $result;
}
}else{
throw new Exception("First need prepareSQL");
}
}
/**
*
* Metodo publico para retornar o resultado de uma query qualquer
* Verifica se a query e um SELECT e retorna um array associativo
* se a query for INSERT retorna o lastId se for update ou delete retorna afected
* @access public
* @input string
* @return mixed
*
*/
final public function executeSql($sql) {
self::__prepare($sql);
if ($this->queryType == "select") {
self :: __setSql($sql);
return self :: getAssocArray();
} else {
return self :: __setSql($sql);
}
}
/**
*
* Metodo privado para query do tipo SELECT
* Prepara e executa SELECT
* @access private
* @input SQL {string}
* @return Obj
*
*/
private function __selectQuery($sql,$param=null) {
if ($this->queryType == "select") {
return self::__execute($param);
} else {
throw new Exception("Não é SELECT =>SQL:[".$sql."] ");
}
}
/**
*
* Metodo privado para query condicionais
* Executa query condicionais para query UPDATE e DELETE
* @access private
* Retorna o numero de resultados afetados
* @input SQL {string}
* @return numero de resultados afetados, number of affected rows, {int}
*
*/
private function __conditionalQuery($sql,$param=null) {
if (stripos(strtolower($sql), 'where') == true) {
self::__execute($param);
try {
return $this->sth->rowCount();
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :\"".$e->getMessage());
}
} else {
throw new Exception("Eh necessário a clausula WHERE =>SQL:[".$sql."] ");
}
}
/**
*
* Metodo privado para query do tipo INSERT
* Executa query INSERT e retorna o ID inserido
* @access private
* Retorna o numero ID inserido
* @input SQL {string}
* @return lastInsertId {int}
*
*/
private function __insertQuery($sql,$param=null) {
if ($this->queryType == "insert") {
self::__execute($param);
try {
return $this->objPdo->lastInsertId();
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :".$e->getMessage()."=>SQL:[".$sql."] ");
}
} else {
throw new Exception("Não é INSERT=>SQL:[".$sql."] ");
}
}
/**
*
* Metodo publico para setar a query
* Decide o metodo de acordo com o tipo de SQL
* @access public
* @input SQL {string}
* @return Obj
*
*/
private function __setSql($sql,$param=null) {
switch (self :: __queryType($sql)) {
case "select";
return self :: __selectQuery($sql,$param); // Para testes basta retirar os comentarios
break;
case "update";
case "delete";
return self :: __conditionalQuery($sql,$param);
break;
case "insert";
return self :: __insertQuery($sql,$param);
break;
default :
throw new Exception("Query não suportada =>SQL:[".$sql."]\r\n<br/>");
break;
}
}
/**
*
* Metodo publico para retornar um array associativo
* Verifica se a query e um SELECT e retorna um array associativo
* @access public
* @input
* @return array
*
*/
final public function getAssocArray() {
unset ($rows);
unset ($results);
try{
self::__selectQuery($this->sqlPrepare);
try {
while ($rows = $this->sth->fetch(PDO::FETCH_ASSOC)) {
$results[] = $rows;
}
return $results;
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :\"".$e->getMessage()."\"");
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
* Metodo publico para retornar uma linha com um array associativo
* Verifica se a query e um SELECT e retorna um array associativo
* @access public
* @input
* @return array
*/
final public function getLineArray() {
unset ($results);
try{
self::__selectQuery($this->sqlPrepare);
try {
$results= $this->sth->fetch();
return $results;
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :\"".$e->getMessage()."\"");
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
*
* Metodo publico para retornar um resultado especifico de uma coluna
* Verifica se a query e um SELECT e retorna o valor de um campo
* @access public
* @input number ,optional array[key]
* @return string (array[key]=>value)
*
*/
final public function getRow($row = 0) {
if ($this->queryType == "select") {
self :: __selectQuery($this->sqlPrepare);
try {
$result = $this->sth->fetchColumn($row);
} catch (PDOException $e) {
throw new Exception("[".$this->sth->errorCode()."] MSG :\"".$e->getMessage());
}
return $result;
} else {
throw new Exception("SELECT não definido para uso de getRow defina setSql");
}
}
public function beginTransaction() {
$transaction = $this->objPdo->beginTransaction();
}
#
public function commit() {
$commit = $this->objPdo->commit();
}
#
public function rollBack() {
$rollBack = $this->objPdo->rollBack();
}
/**
*
* Previne que o usuário clone a instância
* @access public
*
*/
public function __clone() {
throw new Exception("Clone is not allowed.");
}
# fim da classe
}
class DataBasePdoStatement extends PDOStatement {
}
?>