Classe CRUD com PDO
Buenas pessoal, tudo belezinha? :joia:
Seguinte, comecei a desenvolver uma classe para usar em futuros trabalhos, como é a primeira vez que trabalho com Classe e PDO gostaria da opinião de vocês como posso melhorar o meu código e também verificar os erros do mesmo.
Nessa classe tem uma função que grava logs após usar as funções: Insert, Update, Delete.
Alguém disposto a me ajudar??? :clover:
Segue as classes:
Classe PDO (Connect.inc.php)
<?php
class BD{
private $ConnHost;
private $ConnUser;
private $ConnPass;
private $ConnDb;
private $ConnDriver;
function __construct(){
$this->ConnDriver = "mysql";
$this->ConnHost = "localhost";
$this->ConnUser = "root";
$this->ConnPass = "root";
$this->ConnDb = "testes";
}
function Connect(){
$conn = NULL;
try{
$conn = new PDO($this->ConnDriver.":host=".$this->ConnHost.";dbname=".$this->ConnDb,$this->ConnUser,$this->ConnPass);
}catch (PDOException $e){
$e->getMessage();
echo "Atenção! Ocorreu um erro ao tentar se conectar ao banco de dados.<br />Caso o erro persistir contate o administrador do sistema!";
exit();
}
return $conn;
}
}
?>
Classe CRUD (CRUD.class.php)
<?php
//Classe para conexao BD
include_once("Connect.inc.php");
/***
*
*
* @category Class for Create, Read, Update and Delete (CRUD)
* @author Marcelo Garbin <marcelo.garbin@hotmail.com>
* @copyright 2013 - Marcelo Garbin
* @version 1.0
*
*
***/
class CRUD{
//CRUD
private $SQL;
private $LogSQL;
private $Table;
private $TFields;
private $TValues;
private $Query;
//Set table log
private $TLogs;
function __construct(){
$this->SQL = NULL;
$this->LogSQL = NULL;
$this->Table = NULL;
$this->TFields = NULL;
$this->TValues = NULL;
$this->Query = NULL;
//Set table log
$this->TLogs = "logs_system";
}
function Insert(){
try{
//Dados
$table = self::GetTable();
$campos = self::GetTFields();
$valores = self::GetTValues();
$fields = NULL;
$values = NULL;
$FieldValue = array_combine($campos,$valores);
//Separa campos
foreach($FieldValue as $field => $value){
$fields .= $field.', ';
$values .= $value.', ';
}
//Remove o espaço e virgula final
$fields = substr($fields, 0, strlen($fields)-2);
$values = substr($values, 0, strlen($values)-2);
if(!empty($table) && !empty($fields)){
if(!empty($table) && !empty($fields) && !empty($valores)){
//Cria objeto e abre conexão
$pdo = new BD;
$pdo = $pdo->Connect();
//Monta SQL para insert
self::SetSQL("INSERT INTO ".$table." (".str_replace(':','', $fields).")"." VALUES "."(".$fields.");");
//Prepara Insert
$stmt = $pdo->prepare(self::GetSQL());
//Trata entrada de dados
foreach($FieldValue as $field => $value){
$stmt->bindValue($field, $value);
}
//Executa o metodo
if($stmt->execute() && $stmt->rowCount() > 0){
//Monta SQL para Log
self::SetLogSQL("INSERT INTO ".$table." (".str_replace(':','', $fields).")"." VALUES "."(".$values.");");
//Seta o log e sua acao
self::SetLogs('INSERT');
return true;
}else{
return false;
}
}else{
echo '<br /><strong>Erro: </strong>Faltam complementos para executar a ação!<br />';
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo = NULL;
$table = NULL;
$campos = NULL;
$valores = NULL;
$fields = NULL;
$values = NULL;
}
function Update($id){
try{
//Dados
$table = self::GetTable();
$campos = self::GetTFields();
$valores = self::GetTValues();
$fields = NULL;
$values = NULL;
$FieldValue = array_combine($campos,$valores);
//Separa campos
foreach($FieldValue as $field => $value){
$field = str_replace(':','', $field);
$fields .= $field.'=:'.$field.', ';
$values .= $field.'=\''.$value.'\', ';
}
//Remove o espaço e virgula final
$fields = substr($fields, 0, strlen($fields)-2);
$values = substr($values, 0, strlen($values)-2);
if(!empty($table) && !empty($fields)){
if(!empty($table) && !empty($fields) && !empty($valores)){
//Cria objeto e abre conexão
$pdo = new BD;
$pdo = $pdo->Connect();
//Verifica se id existe no BD
$stmt = $pdo->prepare("SELECT * FROM ".$table." WHERE id=:id");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
if($stmt->rowCount() > 0){
//Monta SQL para insert
self::SetSQL("UPDATE ".$table." SET ".$fields." WHERE id=:id;");
//Prepara Insert
$stmt = $pdo->prepare(self::GetSQL());
//Trata entrada de dados
foreach($FieldValue as $field => $value){
$stmt->bindValue($field, $value);
}
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
//Executa o metodo
if($stmt->execute() && $stmt->rowCount() > 0){
//Monta SQL para Log
self::SetLogSQL("UPDATE ".$table." SET ".$values." WHERE id=".$id.";");
//Seta o log e sua acao
self::SetLogs('UPDATE');
return true;
}else{
return false;
}
}else{
echo '<br /><strong>Error: </strong>Record not found in our database!<br />';
}
}else{
echo '<br /><strong>Error: </strong>Insufficient ons to perform the action!<br />';
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo = NULL;
$table = NULL;
$campos = NULL;
$valores = NULL;
$fields = NULL;
$values = NULL;
}
function Delete($id){
try{
//Dados
$table = self::GetTable();
if(!empty($id)){
//Cria objeto e abre conexão
$pdo = new BD;
$pdo = $pdo->Connect();
//Verifica se id existe no BD
$stmt = $pdo->prepare("SELECT * FROM ".$table." WHERE id=:id");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
if($stmt->rowCount() > 0){
//Monta SQL para insert
self::SetSQL("DELETE FROM ".$table." WHERE id=:id;");
//Prepara Insert
$stmt = $pdo->prepare(self::GetSQL());
//Trata entrada de dados
$stmt->bindValue(':id', $id);
//Executa o metodo
if($stmt->execute() && $stmt->rowCount() > 0){
//Monta SQL para Log
self::SetLogSQL("DELETE FROM ".$table." WHERE id=".$id.";");
//Seta o log e sua acao
self::SetLogs('DELETE');
return true;
}else{
return false;
}
}else{
echo '<br /><strong>Erro: </strong>Registro não encontrado no banco de dados!<br />';
}
}else{
echo '<br /><strong>Erro: </strong>Faltam complementos para executar a ação!<br />';
}
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo = NULL;
$table = NULL;
$id = NULL;
}
function Select($query){
try{
//Dados
self::SetQuery($query);
if(!empty($query)){
//Cria objeto e abre conexão
$pdo = new BD;
$pdo = $pdo->Connect();
//Verifica se query e valida
if($stmt = $pdo->query(self::GetQuery())){
//Retorna todos os valores ref. a query
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $res;
}else{
echo '<br /><p><strong>Error: </strong>Invalid Query, check the SQL code!<br /></p>';
return false;
}
}
}catch(Exception $e){
echo $e->getMessage();
}
$pdo = NULL;
}
function SetLogs($acao){
try{
//Cria objeto e abre conexão
$pdo = new BD;
$pdo = $pdo->Connect();
//Prepata insert
$stmt = $pdo->prepare("INSERT INTO ".$this->TLogs."(ip_remote, login, password, action, action_sql, date_time) VALUES (:ip_remote, :login, :password, :action, :action_sql, NOW())");
//Trata entrada de dados
$stmt->bindValue(':ip_remote', $_SERVER['REMOTE_ADDR']);
$stmt->bindValue(':login', $login=null);
$stmt->bindValue(':password', $senha=null);
$stmt->bindValue(':action', $acao);
$stmt->bindValue(':action_sql', self::GetLogSQL());
//Executa o metodo
$stmt->execute();
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo = NULL;
}
/* ////// */
/* Set's */
/* //// */
function SetTable($table = NULL){
$this->Table = $table;
}
function SetTFields($campos = NULL){
$this->TFields = $campos;
}
function SetTValues($valores = NULL){
$this->TValues = filter_var_array(array_map("htmlspecialchars",$valores), FILTER_SANITIZE_STRING);
}
function SetSQL($sql = NULL){
$this->SQL = $sql;
}
function SetLogSQL($sql = NULL){
$this->LogSQL = $sql;
}
function SetQuery($query = NULL){
$this->Query = $query;
}
/* ////// */
/* Get's */
/* //// */
function GetTable(){
return $this->Table;
}
function GetTFields(){
return $this->TFields;
}
function GetTValues(){
return $this->TValues;
}
function GetSQL(){
return $this->SQL;
}
function GetLogSQL(){
return $this->LogSQL;
}
function GetQuery(){
return $this->Query;
}
}
?>Discussão (45)
Carregando comentários...