Omar, não sei como usar a classe Select (para filtrar), Update e Delete do seu projeto
arquivo /omar2/controles/controle.php
<?php
class controle {
public function consultar(){
$select=new Select;
$select->query('usuários');
$teste=$select->result();
var_dump($teste);
$this->voltar();}
public function filtrar(){
$select=new Select;
$select->genérico("select * from usuários where nome like 'frank%'");
$teste=$select->result();
var_dump($teste);
$this->voltar();}
public function adicionar(){
$insert=new Insert();
$insert->query("usuários",["id"=>3,"nome"=>"teste","email"=>"teste@uol.com.br","senha"=>"JamesBond"]);
$teste=$insert->error();
var_dump($teste);
$this->voltar();}
public function atualizar(){
$update=new Update();
$update->genérico('update usuários set nome="outro teste" where id=3');
$teste=$update->error();
var_dump($teste);
$this->voltar();}
public function excluir(){
$delete=new Delete();
$delete->genérico('delete from usuários where id=3');
$teste=$delete->error();
var_dump($teste);
$this->voltar();}
public function voltar(){
echo "<input type=submit value=Voltar onclick=location.replace('index.php')>";
exit;}}
$controle=new controle();
if(isset($_GET)){
$get=$_GET;
if(empty($get)){return;}
if($get['url']=="consultar"){$controle->consultar();}
if($get['url']=="filtrar"){$controle->filtrar();}}
if($get['url']=="adicionar"){$controle->adicionar();}
if($get['url']=="atualizar"){$controle->atualizar();}
if($get['url']=="excluir"){$controle->excluir();}
arquivo /omar2/index.php
<?php
require 'visões/index.php';
arquivo /omar2/modelos/Connect.php
<?php
class Connect {
private static $host = DB_HOST;
private static $user = DB_USER;
private static $pass = DB_PASS;
private static $data = DB_DATA;
private static $isConnect = null;
private static $isError = null;
private static function makeConnect() {
try {
if (self::$isConnect == null) {
$dsn = 'mysql:host=' . self::$host . '; dbname=' . self::$data;
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
self::$isConnect = new PDO($dsn, self::$user, self::$pass, $options); }
} catch (PDOException $e) {
self::$isError = '<br>Não foi possível conectar com o banco de dados!<br> Descrição:' . $e->getMessage() . '<br>';
//die('Erro interno no servidor. Código de referência 500');
die($e->getMessage()); }
self::$isConnect->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return (self::$isConnect); }
protected static function callConnect() {
return (self::makeConnect()); }
protected static function getError() {
if (self::$isError) {
return (self::$isError);}}}
arquivo /omar2/modelos/Delete.php
<?php
class Delete extends Connect {
private $deleteTable;
private $deleteFields;
private $deleteValues;
private $deleteSyntax;
private $deleteConn;
private $deleteData;
private $deleteError;
public function genérico($deletar){
$this->deleteSyntax=$deletar;
$this->deleteExecute();}
public function query($table, $fields, $statements) {
$this->deleteTable = (string) $table;
$this->deleteFields = (string) $fields;
parse_str($statements, $this->deleteValues);
$this->deleteConstruct();
$this->deleteExecute(); }
public function count() {
if ($this->deleteData) {
return ($this->deleteSyntax->rowCount());} else {
return (0);}}
public function result() {
if ($this->deleteData) {
return ($this->deleteData);}}
public function error() {
if (!$this->deleteData) {
return ($this->deleteError);}}
private function deleteConstruct() {
$this->deleteSyntax = "DELETE FROM {$this->deleteTable} WHERE {$this->deleteFields}";}
private function deleteConnect() {
$this->deleteConn = parent::callConnect();
$this->deleteSyntax = $this->deleteConn->prepare($this->deleteSyntax);}
private function deleteExecute() {
$this->deleteConnect();
try {
$this->deleteSyntax->execute($this->deleteValues);
$this->deleteData = true;
} catch (PDOException $error) {
$this->deleteData = null;
$this->deleteError = "Erro ao ler dados: {$error->getMessage()} {$error->getCode()}";}}}
arquivo /omar2/modelos/GlobalFilter.php
<?php
class GlobalFilter {
public static function StdArray($array) {
$object = new stdClass();
if (is_array($array)) {
foreach ($array as $name => $value) {
$object->$name = $value;}}
return $object;}
public static function ObjArray($array) {
if (is_array($array)) {
//return (object) array_map(__FUNCTION__, $array);
return (object) array_map(__METHOD__, $array);} else {
return $array;}}
public static function filterGet() {
$filterGet = filter_input_array(INPUT_GET, FILTER_DEFAULT);
$filter = isset($filterGet) ? self::StdArray($filterGet) : false;
return ($filter);}
public static function filterPost() {
$filterPost = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$filter = isset($filterPost) ? self::StdArray($filterPost) : false;
return ($filter);}
public static function filterSession() {
$filterSession = filter_input_array(INPUT_SESSION, FILTER_DEFAULT);
$filter = isset($filterSession) ? self::StdArray($filterSession) : false;
return ($filter);}
public static function filterCookie() {
$filterCookie = filter_input_array(INPUT_COOKIE, FILTER_DEFAULT);
$filter = isset($filterCookie) ? self::StdArray($filterCookie) : false;
return ($filter);}
public static function filterServe() {
$filterServe = filter_input_array(INPUT_SERVER, FILTER_DEFAULT);
$filter = isset($filterServe) ? self::StdArray($filterServe) : false;
return ($filter);}
public static function filterEven() {
$filterEven = filter_input_array(INPUT_ENV, FILTER_DEFAULT);
$filter = isset($filterEven) ? self::StdArray($filterEven) : false;
return ($filter);}
public static function filterRequest() {
$filterRequest = filter_input_array(INPUT_REQUEST, FILTER_DEFAULT);
$filter = isset($filterRequest) ? self::StdArray($filterRequest) : false;
return ($filter);}}
arquivo /omar2/modelos/Insert.php
<?php
class Insert extends Connect {
private $insertTable;
private $insertFilds;
private $insertSyntax;
private $insertConn;
private $insertData;
private $insertError;
public function query($table, array $fields) {
$this->insertTable = (string) $table;
$this->insertFilds = $fields;
$this->insertConstruct();
$this->insertExecute(); }
public function count() {
if ($this->insertData) {
return ($this->insertSyntax->rowCount());} else {
return (0);}}
public function result() {
if ($this->insertData) {
return ($this->insertData);}}
public function error() {
if (!empty($this->insertError)) {
return ($this->insertError);}}
private function insertConstruct() {
$Column = implode(', ', array_keys($this->insertFilds));
$values = ':' . implode(', :', array_keys($this->insertFilds));
$this->insertSyntax = "INSERT INTO {$this->insertTable} ({$Column}) VALUES ({$values})";}
private function insertConnect() {
$this->insertConn = parent::callConnect();
$this->insertSyntax = $this->insertConn->prepare($this->insertSyntax);}
private function insertExecute() {
$this->insertConnect();
try {
$this->insertSyntax->execute($this->insertFilds);
$this->insertData = $this->insertConn->lastInsertId();
} catch (PDOException $error) {
$this->insertData = null;
$this->insertError = "Erro ao inserir dados: {$error->getMessage()} {$error->getCode()}";}}}
arquivo /omar2/modelos/LogRegister.php
<?php
class LogRegister {
private static $file;
private static $message;
private static $comment;
public static function dataError($file, $message, $comment = null) {
self::$file = (string) $file;
self::$message = (string) $message;
self::$comment = (string) $comment;
if (!empty($file) && !empty($message)) {
self::registerError();}}
private static function registerError() {
$lgErr = new Select();
$lgErr->query('log_error', [
'lg_date' => date('Y-m-d'),
'lg_hour' => date('H:i:s'),
'lg_file' => self::$file,
'lg_message' => htmlentities(self::$message),
'lg_comment' => htmlentities(self::$comment)]);
if ($lgErr->error()) {
self::sqlError();}}
private static function sqlError() {
$txt = "== [ ERROR ] ===========================\n"
. "- Data: " . date('Y-m-d') . "\n"
. "- Horário: " . date('H:i:s') . "\n"
. "- Arquivo: " . self::$file . "\n"
. (!empty(self::$message) ? "- Mensagem:\n" . strip_tags(self::$message) . "\n" : "")
. (!empty(self::$comment) ? "\n- Comentários:\n" . strip_tags(self::$comment) : "")
. "\n";
$reg = fopen(MODELO_DIR . 'error.log', 'a');
fwrite($reg, $txt);
fclose($reg);}}
arquivo /omar2/modelos/Select.php
<?php
class Select extends Connect {
private $selectTable;
private $selectFields;
private $selectSyntax;
private $selectConn;
private $selectData;
private $selectError;
public function genérico($consulta){
$this->selectTable=$consulta;
$this->selectExecute();}
public function query($table, $fields = null, $statements = null) {
if (!empty($statements)) {
parse_str($statements, $this->selectFields);}
$this->selectTable = 'SELECT * FROM ' . $table . (isset($fields) ? ' WHERE ' . $fields : null);
$this->selectExecute();}
public function setQuery($Query, $statements = null) {
if (!empty($statements)) {
parse_str($statements, $this->selectFields); }
$this->selectTable = (string) $Query;
$this->selectExecute(); }
public function count() {
return ($this->selectSyntax->rowCount());}
public function result() {
if ($this->selectData) {
return ($this->selectData);}}
public function error() {
if (!empty($this->selectError)) {
return ($this->selectError);}}
private function selectConstruct() {
if ($this->selectFields) {
foreach ($this->selectFields as $type => $value) {
if ($type == 'limit' || $type == 'offset') {
$value = (int) $value;}
$this->selectSyntax->bindValue(":{$type}", $value, (is_int($value) ?
PDO::PARAM_INT : PDO::PARAM_STR));}}}
private function selectConnect() {
$this->selectConn = parent::callConnect();
$this->selectSyntax = $this->selectConn->prepare($this->selectTable);
$this->selectSyntax->setFetchMode(PDO::FETCH_OBJ);}
private function selectExecute() {
$this->selectConnect();
try {
$this->selectConstruct();
$this->selectSyntax->execute();
$this->selectData = $this->selectSyntax->fetchAll();
} catch (PDOException $error) {
$this->selectData = null;
$this->selectError = "Erro ao ler dados: {$error->getMessage()} {$error->getCode()}";}}}
arquivo /omar2/modelos/Session.php
<?php
class Session {
private static $status;
private static $globalName;
private static $session;
public static function startSession($prefix = null) {
self::$globalName = (empty($prefix) ? null : '_' . $prefix);
if (!self::$status) {
self::$session = new self; }
self::$status = session_start();
return (self::$session);}
public static function getSession() {
return (self::$status);}
public static function destroy() {
self::$session = session_destroy();
unset($_SESSION);}
public function __set($name, $value) {
$_SESSION[$name . self::$globalName] = $value;}
public function __get($name) {
if (isset($_SESSION[$name . self::$globalName])) {
return ($_SESSION[$name . self::$globalName]);}}
public function __isset($name) {
return (isset($_SESSION[$name . self::$globalName]));}
public function __unset($name) {
unset($_SESSION[$name . self::$globalName]);}}
arquivo /omar2/modelos/Update.php
<?php
class Update extends Connect {
private $updateTable;
private $updateColumn = [];
private $updateFields;
private $updateValues = [];
private $updateSyntax;
private $updateConn;
private $updateError;
private $updateData;
public function genérico($atualização){
$this->updateSyntax=$atualização;
$this->updateExecute($atualização);}
public function query($table, array $change, $target, $statements) {
$this->updateTable = (string) $table;
$this->updateColumn = $change;
$this->updateFields = (string) $target;
parse_str($statements, $this->updateValues);
$this->updateConstruct();
$this->updateExecute();}
public function setQuery($query, $statements = null) {
if (!empty($statements)) {
parse_str($statements, $this->updateValues); }
$this->updateSyntax = $query;
$this->updateExecute();}
public function count() {
if ($this->updateData) {
return ($this->updateSyntax->rowCount());} else {
return (0);}}
public function error() {
if (!empty($this->updateError)) {
return ($this->updateError);}}
private function updateConstruct() {
foreach ($this->updateColumn as $Key => $Value) {
$setKey[] = $Key . ' = :' . $Key;}
$Value = array();
$setKey = implode(', ', $setKey);
$this->updateSyntax = "UPDATE {$this->updateTable} SET {$setKey} WHERE {$this->updateFields}";}
private function updateConnect() {
$this->updateConn = parent::callConnect();
$this->updateSyntax = $this->updateConn->prepare($this->updateSyntax);}
private function updateExecute() {
$this->updateConnect();
try {
$this->updateSyntax->execute(array_merge($this->updateColumn, $this->updateValues));
$this->updateData = true;
} catch (PDOException $error) {
$this->updateData = false;
$this->updateError = "Erro ao alterar dados: {$error->getMessage()} {$error->getCode()}";}}}
arquivo /omar2/modelos/config.php
<?php
error_reporting(E_ALL);
ini_set('ignore_repeated_errors', TRUE);
ini_set('display_errors', TRUE);
ini_set('log_errors', TRUE);
ini_set('error_log', __DIR__ . '/error.log');
ob_start();
defined('MODELO_DIR') || define('MODELO_DIR',$_SERVER['DOCUMENT_ROOT'] .'/omar2/modelos/');
defined('CONTROLE_DIR') || define('CONTROLE_DIR',$_SERVER['DOCUMENT_ROOT'].'/omar2/controles/');$con = [
'ready' => true,
'dbHost' => 'localhost',
'dbUser' => 'root',
'dbPass' => '',
'dbName' => 'mvc'];$setting = [
'ready' => true,
'siteName' => 'Meu website',
'charset' => 'UTF-8'];try {
if (!isset($con['ready'])) {
throw new Exception('Dados de configurações para conexão não definidos', E_ERROR);
} else if (!isset($setting['ready'])) {
throw new Exception('Dados de configurações de comportamento não definidos', E_ERROR);
} else {
defined('DB_HOST') || define('DB_HOST', $con['dbHost']);
defined('DB_USER') || define('DB_USER', $con['dbUser']);
defined('DB_PASS') || define('DB_PASS', $con['dbPass']);
defined('DB_DATA') || define('DB_DATA', $con['dbName']);
defined('SITE_NAME') || define('SITE_NAME', $setting['siteName']);
date_default_timezone_set('America/Sao_Paulo');
spl_autoload_register(function ($class) {
$includeDir = false;
$findDir = ['controles','modelos','visões'];
foreach ($findDir as $DirName) {
if (!$includeDir
&& file_exists(FindClass($DirName, $class))
&& !is_dir(FindClass($DirName, $class))) {
include_once (FindClass($DirName, $class));
$includeDir = true;}}
if (!$includeDir) {
die("Erro interno no servidor ao encontrar dados cruciais de funcionamento!");}});
function FindClass($dir, $class) {
return (
$_SERVER['DOCUMENT_ROOT']
. DIRECTORY_SEPARATOR . 'omar2'
. DIRECTORY_SEPARATOR . $dir
. DIRECTORY_SEPARATOR . $class . '.php');}
$session = Session::startSession(SITE_NAME);
$config = GlobalFilter::ObjArray($setting);}}
catch (Exception $e) {header('location : http500/');}
arquivo /omar2/visões/index.php
<!DOCTYPE html>
<html>
<head>
<?php
require $_SERVER['DOCUMENT_ROOT']."/omar2/modelos/config.php";
$serve = filter_input_array(INPUT_SERVER, FILTER_DEFAULT);
$rootUrl = strlen($serve['DOCUMENT_ROOT']);
$fileUrl = substr($serve['SCRIPT_FILENAME'], $rootUrl, -9);
if ($fileUrl[0] == '/') {$baseUri = $fileUrl;} else {
$baseUri = '/' . $fileUrl;} ?>
<base href="<?= $baseUri ?>" />
<meta charset="<?=$setting['charset']?>" />
<title><?= SITE_NAME ?></title>
</head>
<body>
<?php
$filter = filter_input(INPUT_GET, 'url', FILTER_DEFAULT);
$setUrl = empty($filter) ? 'consultar' : $filter;
$explode = explode('/', $setUrl);
$url = array_filter($explode);
$request=$url[0];
$map = ['consultar','filtrar','adicionar','atualizar','excluir'];
$file = false;
foreach ($map as $value) {
if (($request == $value) || (is_array($value) && in_array($request, $value))) {
$opção = $value; break; }}
if ($opção) {require CONTROLE_DIR."controle.php";}?>
<table style="width:500;margin:0 auto;margin-top:100px">
<tr><th>Trabalhando com a tabela usuários
<tr><td><a href="?url=consultar">consultar</a>
<tr><td><a href="?url=filtrar">filtrar</a>
<tr><td><a href="?url=adicionar">adicionar</a>
<tr><td><a href="?url=atualizar">atualizar</a>
<tr><td><a href="?url=excluir">excluir</a>
</body>
</html>
O seu autoload é excelente, mas eu não tenho coragem de usar a constante __DIR__.Discussão (2)
Carregando comentários...