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 joao b silva
      Tenho uma pequena aplicação em php que gera arquivos pdf com a MPDF e envia email com a PHPMAILER. De repente a app parou de enviar os emails  e apresenta a seguinte mensagem de erro:
       
      Error PHPMailer: SMTP Error: Could not authenticate.
       
      Faço uso de um hotmail para a configuração do PHPMAILER.
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de tirar uma dúvida com os amigos.
       
      Quando programava em DOS. utilizava algumas teclas de atalho para: SALVAR / EDITAR / EXCLUIR / IMPRIMIR.
      Por exemplo:
      Salvar ----> ALT+S
      Editar ----> ALT+E
      Excluir --> ALT+X
      Imprimir -> ALT+I

      no PHP tem como colocar esses ATALHOS nos button, para o usuário trabalhar com esses atalhos e como seria ?

      grato,
       
      Cesar
    • Por violin101
      Caros Amigos, saudações.
       
      Por favor, me perdoa em postar uma dúvida.
       
      Preciso criar uma Rotina onde o usuário possa buscar na Base de Dados de Produtos, tanto por Código e Descrição, ou seja:
      - caso o usuário digita o Código, mostra os dados do Produto.
      - caso o usuário digita a Descrição, mostra os dados do Produto
       
      Fiz uma Rotina, onde o usuário digita a DESCRIÇÃO com a função AUTOCOMPLETE.    <=== está funcionando certinho.
       
      Minha dúvida é como faço para DIGITAR o Código e mostrar os dados também.
       
      o meu AutoComplete na MODEL está assim.
      public function autoCompleteProduto($q){ $this->db->select('*' ) ->from('produtos') ->where('produtos.statusProd',1) ->like('descricao', $q) ->limit(5) ->order_by('descricao', 'ASC'); $query = $this->db->get(); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { $row_set[] = ['label' => str_pad($row['idProdutos'], '5', '0', STR_PAD_LEFT).' - '.$row['descricao'], 'id' => $row['idProdutos'], 'descricao' => $row['descricao'], 'cod_interno' => $row['cod_interno'], 'prd_unid' => $row['prd_unid'], 'estoque_atual' => $row['estoque_atual'] ]; } echo json_encode($row_set); } }  
       
      no CONTROLLER está assim:
      public function autoCompleteProduto() { $this->load->model('estoque/lancamentos_model'); if (isset($_GET['term'])) { $q = strtolower($_GET['term']); $this->lancamentos_model->autoCompleteProduto($q); } }  
       
      na VIEW está assim:
      <div class="col-md-10"> <label for="idProdutos">Produto:</label> <input type="hidden" name="idProdutos" id="idProdutos"> <input type="text" class="form-control" id="descricao" name="descricao" style="font-size:15px; font-weight:bold;" placeholder="Pesquisar por descrição do produto" disabled> </div>  
      VIEW + JAVASCRIPT
       
      //Função para trazer os Dados pelo o AutoComplete. function resolveAutocomplete() { $("#descricao").autocomplete({ source: "<?php echo base_url(); ?>estoque/lancamentos/autoCompleteProduto/", minLength: 2, select: function (event, ui) { $("#idProdutos").val(ui.item.id); $("#cod_interno").val(ui.item.cod_interno); $("#descricao").val(ui.item.descricao); $("#prd_unid").val(ui.item.prd_unid); $("#estoque_atual").val(ui.item.estoque_atual); $("#qtde").focus(); } }); } // inicia o autocomplete resolveAutocomplete();  
      Grato,
       
      Cesar
    • Por belann
      Olá!
       
      Estou tentando criar um projeto laravel e está dando o seguinte erro 
      curl error 60 while downloading https://getcomposer.org/versions: SSL certificate problem: unable to get local issu
        er certificate
      Já tentei atualizar o composer, mas dá o mesmo erro acima.
    • Por violin101
      Caros amigos, saudações.
       
      Estou com uma dúvida de validação de INPUT com função moeda.
       
      Tenho um input onde o usuário digita um valor qualquer, por exemplo: 1.234,56
      o problema é quando precisa atualizar o valor.
       
      Quando o usuário atualizar o input fica assim: 1.234,
       
      como faço para atualizar as casas decimais, conforme o valor for sendo alterado ?
       
      o input está assim:
       
      <div class="col-md-2"> <label for="">Valor Unitário</label> <input type="text" class="form-control" id="estoqprod" name="estoqprod" style="font-size:15px; font-weight:bold; width:100%; text-align:center;" placeholder="0,00" OnKeyUp="calcProd();" onkeypress="return(FormataMoeda(this,'.',',',event))" > </div>  
      a função para formatar o input para moeda está assim:
      obs.: a Função CalcProd está executando corretamente
      function calcProd(){ //Obter valor digitado do produto var estoq_prod = document.getElementById("estoqprod").value; //Remover ponto e trocar a virgula por ponto while (estoq_prod.indexOf(".") >= 0) { estoq_prod = estoq_prod.replace(".", ""); } estoq_prod = estoq_prod.replace(",","."); //Obter valor digitado do produto var prod_qtde = document.getElementById("qtde").value; //Remover ponto e trocar a virgula por ponto while (prod_qtde.indexOf(".") >= 0) { prod_qtde = prod_qtde.replace(".", ""); } prod_qtde = prod_qtde.replace(",","."); //Calcula o Valor do Desconto if (prod_qtde > 0 && estoq_prod > 0) { calc_total_produto = parseFloat(prod_qtde) - parseFloat(estoq_prod); var numero = calc_total_produto.toFixed(2).split('.'); //Calculo para não deixar GRAVAR valores negativos if (calc_total_produto < 0 ) { numero[0] = numero[0].split(/(?=(?:...)*$)/).join('.') * -1; document.getElementById("qtdeTotal").value = numero.join(','); } else { numero[0] = numero[0].split(/(?=(?:...)*$)/).join('.'); document.getElementById("qtdeTotal").value = numero.join(','); } } else { if (estoq_prod > 0) { document.getElementById("qtdeTotal").value = document.getElementById("estoqprod").value; } else { document.getElementById("qtdeTotal").value = "0,00"; } } } /*---Função para Formatar Campo para Moeda [R$]---*/ function FormataMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){ var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (whichCode == 13) return true; key = String.fromCharCode(whichCode); // Valor para o código da Chave if (strCheck.indexOf(key) == -1) return false; // Chave inválida len = objTextBox.value.length; for(i = 0; i < len; i++) if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i); aux += key; len = aux.length; if (len == 0) objTextBox.value = ''; if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux; if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux; if (len > 2) { aux2 = ''; for (j = 0, i = len - 3; i >= 0; i--) { if (j == 3) { aux2 += SeparadorMilesimo; j = 0; } aux2 += aux.charAt(i); j++; } objTextBox.value = ''; len2 = aux2.length; for (i = len2 - 1; i >= 0; i--) objTextBox.value += aux2.charAt(i); objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len); } return false; }  
      Grato,
       
      Cesar
×

Informação importante

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