Ir para conteúdo

POWERED BY:

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 violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de tirar uma dúvida com os amigos, referente a PDV.
       
      Estou escrevendo um Sistema com Ponto de Vendas, a minha dúvida é o seguinte, referente ao procedimento mais correto.

      Conforme o caixa vai efetuando a venda, o Sistema de PDV já realiza:
      a baixa direto dos produtos no estoque
      ou
      somente após concretizar a venda o sistema baixa os produtos do estoque ?
       
      Grato,
       
      Cesar
       
    • Por violin101
      Caros amigos do grupo, saudações e um feliz 2025.
       
      Estou com uma pequena dúvida referente a Teclas de Atalho.

      Quando o Caps Lock está ativado o Comando da Tecla de Atalho não funciona.
      ou seja:
      se estiver para letra minúscula ====> funciona
      se estiver para letra maiúscula ====> não funciona
       
      Como consigo evitar essa falha, tanto para Letra Maiúscula quanto Minúscula ?

      o Código está assim:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'r' ) return;// Não é Ctrl+r, portanto interrompemos o script evt.preventDefault(); });  
      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, poderiam me ajudar.

      Estou com a seguinte dúvida:
      --> como faço para para implementar o input código do produto, para quando o usuário digitar o ID o sistema espera de 1s a 2s, sem ter que pressionar a tecla ENTER.

      exemplo:
      código   ----   descrição
           1       -----   produto_A
       
      Grato,
       
      Cesar
×

Informação importante

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