Ir para conteúdo
Frank K Hosaka

Omar, não sei como usar a classe Select (para filtrar), Update e Delete do seu projeto

Recommended Posts

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__.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Como não sei como trabalhar com os objetos criados pelo Omar, encontrei um outro no YouTube, nesse endereço:

https://youtu.be/uG64BgrlX7o?si=TS4Lhe9dWlQGnzY_

 

O código original do YouTube usa o autoload.php criado pelo composer. Eu não usei o composer, preciso saber como trabalhar com o endereço absoluto. No PHP nós temos $_SERVER['DOCUMENT_ROOT'], mas você não pode usar dentro do HTML. Só hoje é que eu aprendi a usar o endereço absoluto no HTML. Se o meu projeto está na pasta Omar2, no HTML faço assim <a href='/Omar2/Controles/Controle.php'>.

Fiz as minhas adaptações. O código é bem simples, ele faz todas as operações do Crud e pedi para voltar à tele inicial. Mas isso não funcionou em alguns comandos. Eu acredito que o comando return que você encontra em muitos objetos acaba encerrando todos os códigos em andamento. O meu código ficou assim:

 


arquivo /Omar2/Controles/Controle.php
<?php
require $_SERVER['DOCUMENT_ROOT']."/Omar2/Modelos/Config.php";
require MODELO."/Users.php";
class Controle {
    public function inicio(){require VISAO."/Index.php";}
    public function consultar(){
        var_dump(Users::getUsers());
        $this->inicio();}
    public function filtrar(){
        var_dump(Users::getUser(1));
        $this->inicio();}
    public function adicionar(){
        $users=new Users();
        var_dump($users->cadastrar('João','joao@gmail.com','JamesBond'));
        $this->inicio();}
    public function atualizar(){
        var_dump((new Users())->atualizar(2,"Maria","maria@gmail.com","JamesBond","2023-12-11 08:33"));
        $this->inicio();}
    public function excluir(){
        var_dump((new Users())->excluir(2));
        $this->inicio();}}
$Controle=new Controle();
if(isset($_GET)){
    $get=$_GET;
    if(key($get)=="consultar"){$Controle->consultar();}
    if(key($get)=="filtrar"){$Controle->filtrar();}}
    if(key($get)=="adicionar"){$Controle->adicionar();}
    if(key($get)=="atualizar"){$Controle->atualizar();}
    if(key($get)=="excluir"){$Controle->excluir();}

arquivo /Omar2/Index.php
<?php
require $_SERVER['DOCUMENT_ROOT']."/Omar2/Modelos/Config.php";
require CONTROLE."/Controle.php";
$controle=New Controle();
$controle->inicio();

arquivo /Omar2/Modelos/Config.php
<?php
date_default_timezone_set("America/Sao_Paulo");
defined('CAMINHO') || define('CAMINHO',$_SERVER['DOCUMENT_ROOT'].'/Omar2');
defined('CONTROLE') || define('CONTROLE',CAMINHO."/Controles");
defined('VISAO') || define('VISAO',CAMINHO."/Visoes");
defined('MODELO') || define('MODELO',CAMINHO."/Modelos");
defined('TITLE') || define('TITLE','Exemplo de CRUD');
defined('HOST') || define('HOST','localhost');
defined('NAME') || define('NAME','laravel');
defined('USER') || define('USER','root');
defined('PASS') || define('PASS','');

arquivo /Omar2/Modelos/Database.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/Omar2/Modelos/Config.php';
class Database{
  const HOST = HOST;
  const NAME = NAME;
  const USER = USER;
  const PASS = PASS;
  private $table,$connection;
  public function __construct($table = null){
    $this->table = $table;
    $this->setConnection();}
  private function setConnection(){
    try{
      $this->connection = new PDO('mysql:host='.self::HOST.';dbname='.self::NAME,self::USER,self::PASS);
      $this->connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
      die('ERROR: '.$e->getMessage());}}
  public function execute($query,$params = []){
    try{
      $statement = $this->connection->prepare($query);
      $statement->execute($params);
      return $statement;
    }catch(PDOException $e){
      die('ERROR: '.$e->getMessage());}}
  public function insert($values){
    $fields = array_keys($values);
    $binds  = array_pad([],count($fields),'?');
    $query = 'INSERT INTO '.$this->table.' ('.implode(',',$fields).') VALUES ('.implode(',',$binds).')';
    var_dump($values);
    $this->execute($query,array_values($values));
    return $this->connection->lastInsertId();}
  public function select($where = null, $order = null, $limit = null, $fields = '*'){
    $where = !empty($where) ? 'WHERE '.$where : '';
    $order = !empty($order) ? 'ORDER BY '.$order : '';
    $limit = !empty($limit) ? 'LIMIT '.$limit : '';
    $query = 'SELECT '.$fields.' FROM '.$this->table.' '.$where.' '.$order.' '.$limit;
    return $this->execute($query);}
  public function update($where,$values){
    $fields = array_keys($values);
    $query = 'UPDATE '.$this->table.' SET '.implode('=?,',$fields).'=? WHERE '.$where;
    $this->execute($query,array_values($values));
    return true;}
  public function delete($where){
    $query = 'DELETE FROM '.$this->table.' WHERE '.$where;
    $this->execute($query);
    return true;}}

arquivo /Omar2/Modelos/MySQL.sql
CREATE TABLE `users` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  `email_verified_at` timestamp NULL DEFAULT NULL,
  `password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `level` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

arquivo /Omar2/Modelos/Users.php
<?php
require_once MODELO."/Database.php";
class Users {
  public $id, $name,$email,$email_verified_at,$password,$remember_token,$created_at,$updated_at,$level;
  public function cadastrar($name,$email,$password){
    $this->name=$name;
    $this->email=$email;
    $this->password=$password;
    $this->created_at = date('Y-m-d H:i:s');
    $obDatabase = new Database('users');
    $this->id = $obDatabase->insert([
      'name'    => $this->name,
      'email' => $this->email,
      'password'     => $this->password,
      'created_at'      => $this->created_at]);
    return true;}
  public function atualizar($id,$name,$email,$password,$created_at){
    $this->id=$id;
    $this->name=$name;
    $this->email=$email;
    $this->password=$password;
    $this->created_at=$created_at;
    return (new Database('users'))->update('id = '.$this->id,[
      'name'    => $this->name,
      'email' => $this->email,
      'password'     => $this->password,
      'created_at'      => $this->created_at]);}
  public function excluir($id){
    $this->id=$id;
    return (new Database('users'))->delete('id = '.$this->id);}
  public static function getUsers($where = null, $order = null, $limit = null){
    return (new Database('users'))->select($where,$order,$limit)
                                  ->fetchAll(PDO::FETCH_CLASS,self::class);}
  public static function getUser($id){
    return (new Database('users'))->select('id = '.$id)
                                  ->fetchObject(self::class);}}

arquivo /Omar2/Visoes/Index.php
<!DOCTYPE html>
<html>
<head>
    <title><?= TITLE ?></title>
</head>
<body>
    <table style="width:500;margin:0 auto;margin-top:100px">
    <tr><th>Trabalhando com a tabela users
    <tr><td><a href="/Omar2/Controles/Controle.php?consultar">consultar</a>
    <tr><td><a href="/Omar2/Controles/Controle.php?filtrar">filtrar</a>
    <tr><td><a href="/Omar2/Controles/Controle.php?adicionar">adicionar</a>
    <tr><td><a href="/Omar2/Controles/Controle.php?atualizar">atualizar</a>
    <tr><td><a href="/Omar2/Controles/Controle.php?excluir">excluir</a>
</body>
</html>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ah, já sei a besteira que eu fiz no código.

Eu escrevi um comando assim:

public function excluir(){
        var_dump((new Users())->excluir(2));
        $this->inicio();}}

Isso está bem errado, o correto é:

public function excluir(){
        $excluir = (new Users())->excluir(2));
		var_dump($excluir);
        $this->inicio();}}

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por landerbadi
      Boa tarde pessoal. Estou tentado fazer uma consulta no banco de dados porém estou tendo dificuldades. Tenho uma tabela chamada "itens" com os seguintes campos: id, item, ativo. Nela tem cadastrado vários itens. No campo ativo eu coloco a letra "S" para informar que este item está ativo no sistema. Por exemplo: 1, casa, S 2, mesa, S 3, cama, S 4, moto S 5, rádio O quinto registro "radio" não está ativo no sistema pois não tem um "S" no campo ativo. E outra tabela chamada "produtos" com os seguintes campos (id, item1, item2, item3) com os seguintes registros: 1, casa, mesa, moto 2, mesa, casa, cama 3, rádio, cama, mesa Eu preciso fazer uma busca na tabela produtos da seguinte maneira: Eu escolho um registro na tabela "itens", por exemplo "mesa". Preciso fazer com que o php me liste todos os registros da tabela "produtos" que contenham a palavra "mesa". Até aqui tudo bem eu consigo listar. Estou fazendo assim: <?php $item = "mesa" $sql = mysqli_query($conn, "SELECT * FROM produtos WHERE item1 LIKE '$item' OR item2 LIKE '$item' OR item3 LIKE '$item' LIMIT 10"); while($aux = mysqli_fetch_assoc($sql)) { $id = $aux["id"]; $item1 = $aux["item1"]; $item2 = $aux["item2"]; $item3 = $aux["item3"]; echo $id . " - " . $item1 . ", " . $item2 . ", " $item3 . "<br>"; } ?> O problema é que está listando todos os registros que contém o item mesa. Eu preciso que o php verifique os demais item e me liste somente os registro em que todos os registros estejam ativos no sistema. No exemplo acima ele não deveria listar o registro 3. pois nesse registro contém o item "radio" e este item não está ativo no sistema. Ou seja, o registro "radio" na tabela itens não possui um "S" na coluna "ativo". Alguém sabe como resolver isso?
    • Por ILR master
      Fala galera.
      Espero que todos estejam bem.
      Seguinte: Tenho um arquivo xml onde alguns campos estão com : (dois pontos), como o exemplo abaixo:
       
      <item>
      <title>
      d sa dsad sad sadasdas
      </title>
      <link>
      dsadas dsa sad asd as dsada
      </link>
      <pubDate>sadasdasdsa as</pubDate>
      <dc:creator>
      d sad sad sa ad as das
      </dc:creator>
      </item>
       
      Meu código:
       
      $link = "noticias.xml"; 
      $xml = simplexml_load_file($link); 
      foreach($xml -> channel as $ite) {     
           $titulo = $ite -> item->title;
           $urltitulo = $ite -> item->link;
           print $urltitulo = $ite -> item->dc:creator;
      } //fim do foreach
      ?>
       
      Esse campo dc:creator eu não consigo ler. Como faço?
       
      Agradeço quem puder me ajudar.
       
      Abs
       
       
    • Por First
      Olá a todos!
       
      Eu estou criando um sistema do zero mas estou encontnrando algumas dificuldades e não estou sabendo resolver, então vim recorrer ajuda de vocês.
      Aqui está todo o meu código: https://github.com/PauloJagata/aprendizado/
       
      Eu fiz um sistema de rotas mas só mostra o conteúdo da '/' não sei porque, quando eu tento acessar o register nada muda.
      E eu também quero que se não estiver liberado na rota mostra o erro de 404, mas quando eu tento acessar um link inválido, nada acontece.
      Alguém pode me ajudar com isso? E se tiver algumas sugestão para melhoria do código também estou aceitando.
       
       
      Desde já, obrigado.
    • Por landerbadi
      Olá pessoal, boa tarde
       
      Tenho uma tabela chamada "produtos" com os seguintes campos (id, produto) e outra tabela chamada "itens" com os seguintes campos (id, prod_01, prod_02, prod_03, prod_04).
       
      Na tabela produtos eu tenho cadastrado os seguintes produtos: laranja, maçã, uva, goiaba, arroz, feijão, macarrão, etc.
       
      Na tabela itens eu tenho cadastrado os itens da seguinte maneira:
       
      1, laranja, uva, arroz, feijão;
      2, maçã, macarrão, goiaba, uva;
      3, arroz, feijão, maçã, azeite
       
      Meu problema é o seguinte: 
      Eu escolho um produto da tabela "produtos", por exemplo "uva".  Preciso fazer uma consulta na tabela "itens" para ser listado todos os registros que contenham o produto "uva" e que todos os demais produtos estejam cadastrados na tabela "produtos".
       
      No exemplo acima seria listado apenas dois registros, pois o terceiro registro não contém o produto "uva". 
       
      Alguém pode me ajudar? Pois estou quebrando a cabeça a vários dias e não consigo achar uma solução.
    • Por landerbadi
      Boa tarde pessoal. Estou tentado fazer uma consulta no banco de dados porém estou tendo dificuldades. Tenho uma tabela chamada "itens" com os seguintes campos: id, item, plural, ativo. Nela tem cadastrado vários itens e seu respectivo plural. No campo ativo eu coloco a letra "S" para informar que esta palavra está ativa no sistema. Por exemplo: 1, casa, casas, S 2, mesa, mesas, S 3, cama, camas, S 4, moto, motos, S 5, rádio, rádios O quinto registro "radio" não está ativo no sistema pois não tem um "S" no campo ativo. E outra tabela chamada "variações" com os seguintes campos (id, item1, item2, item3) com os seguintes registros: 1, casa, camas, moto 2, mesas, casas, radio 3, rádio, cama, mesa Eu preciso fazer uma busca na tabela variações da seguinte maneira: Eu escolho um registro na tabela "itens", por exemplo "casa". Preciso fazer com que o php me liste todos os registros da tabela "variações" que contenham a palavra "casa". Porém se tiver algum registro com a palavra "casas" também tem que ser listado. Neste caso ele irá encontrar dois registros. Agora eu preciso que o php verifique os demais itens e faça a listagem apenas dos item que estão ativos (que contenham um "S" no campo ativo. Neste caso ele irá encontrar apenas um registro, pois o segundo registro contém a palavra "rádio". E "rádio" não está ativo na tabela itens. Como faço isso?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.