Jump to content
Fórum Script Brasil
  • 0

Usar um formulário para cadastrar e também para atualizar


Frank K Hosaka

Question

Ontem eu vi uma parte do vídeo no YouTube https://youtu.be/uG64BgrlX7o?si=AVfbI-4x_CXZsfeK

Ele fala da possibilidade de usar o mesmo formulário tanto para cadastrar uma nova vaga de trabalho, bem como atualizar. Achei interessante.

O problema é que ele usa o Composer para montar o autoload.php e também usa a tecnologia do namespace. Talvez esse seja o segredo, mas eu adaptei o código dele, mas sem usar o Composer:

arquivo /Vagas/Controles/Controle.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/Vagas/Modelos/Config.php';
require MODELO."/Vaga.php";
class Controle {
    public static function inicio(){
        $vagas = Vaga::getVagas();
        include VISAO."/Header.php";
        include VISAO."/Listagem.php";
        include VISAO."/Footer.php";}
    public function cadastrar($post,$fase){
        $obVaga = new Vaga;
        if($fase==2){
            $obVaga->titulo    = $post['titulo'];
            $obVaga->descricao = $post['descricao'];
            $obVaga->ativo     = $post['ativo'];
            $obVaga->cadastrar();
            $this->inicio();
            exit;}
        $id=null;
        include VISAO.'/header.php';
        include VISAO.'/formulario.php';
        include VISAO.'/footer.php';}
    public function excluir($id,$fase){
       if(!isset($id) or !is_numeric($id)){
            $this->inicio();exit;}
        if(isset($id)){
          $obVaga = Vaga::getVaga($id);
          if(!$obVaga instanceof Vaga){
            $this->inicio();exit;}}
       if($fase==2){
            $obVaga=new Vaga();
            $obVaga->excluir($id);
            $this->inicio();exit;}
        include VISAO.'/header.php';
        include VISAO.'/confirmar-exclusao.php';
        include VISAO.'/footer.php';exit;}
    public function editar($id){
        if(!is_array($id)){
            $obVaga = Vaga::getVaga($id);
          if(!$obVaga instanceof Vaga){
            $this->inicio();}}
        if(isset($id['titulo'])){
            $obVaga = Vaga::getVaga($id['id']);
            $obVaga->titulo    = $id['titulo'];
            $obVaga->descricao = $id['descricao'];
            $obVaga->ativo     = $id['ativo'];
            $obVaga->atualizar();
            $this->inicio();
            exit;}
          include VISAO.'/header.php';
          include VISAO.'/formulario.php';
          include VISAO.'/footer.php';}} 
$controle=new Controle();
if(isset($_POST)){
    $post=$_POST;
    if(key($post)=='titulo'){
        if($post['id']==null){
            $controle->cadastrar($post,2);} else {
            $controle->editar($post);}}
    if(key($post)=='id'){$id=$post['id'];$controle->excluir($id,2);}}
if(isset($_GET)){
    $get=$_GET;
    if(key($get)=='Cadastrar'){$controle->cadastrar($get,1);}}
    if(key($get)=='inicio'){$controle->inicio();}
    if(key($get)=='excluir'){$id=$get['excluir'];$controle->excluir($id,1);}
    if(key($get)=='editar'){$id=$get['editar'];$controle->editar($id);}

arquivo /Vagas/Index.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/Vagas/Modelos/Config.php';
require CONTROLE."/Controle.php";
Controle::inicio();


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

arquivo /Vagas/Modelos/Database.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/Vagas/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).')';
    $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 /Vagas/Modelos/MySQL.sql
CREATE TABLE `vagas` (
  `id` int NOT NULL AUTO_INCREMENT,
  `titulo` varchar(255) DEFAULT NULL,
  `descricao` text,
  `ativo` enum('s','n') DEFAULT NULL,
  `data` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

arquivo /Vagas/Modelos/Vaga.php
<?php
require_once MODELO."/Database.php";
class Vaga{
  public $id, $titulo, $descricao, $ativo, $data;
  public function cadastrar(){
    $this->data = date('Y-m-d H:i:s');
    $obDatabase = new Database('vagas');
    $this->id = $obDatabase->insert([
      'titulo'    => $this->titulo,
      'descricao' => $this->descricao,
      'ativo'     => $this->ativo,
      'data'      => $this->data]);
    return true;}
  public function atualizar(){
    return (new Database('vagas'))->update('id = '.$this->id,[
      'titulo'    => $this->titulo,
      'descricao' => $this->descricao,
      'ativo'     => $this->ativo,
      'data'      => $this->data]);}
  public function excluir($id){
    $this->id=$id;
    return (new Database('vagas'))->delete('id = '.$this->id);}
  public static function getVagas($where = null, $order = null, $limit = null){
    return (new Database('vagas'))->select($where,$order,$limit)
                                  ->fetchAll(PDO::FETCH_CLASS,self::class);}
  public static function getVaga($id){
    return (new Database('vagas'))->select('id = '.$id)
                                  ->fetchObject(self::class);}}

arquivo /Vagas/Visoes/Confirmar-exclusao.php
<main>
  <h2 class="mt-3">Excluir vaga</h2>
  <form method="post" action="../Controles/Controle.php">
    <div class="form-group">
      <p>Você deseja realmente excluir a vaga <strong><?=$obVaga->titulo?></strong>?</p>
      <input type=hidden name=id value=<?=$id?>>
    </div>
    <div class="form-group">
      <a href="../Controles/Controle.php?inicio">
        <button type="button" class="btn btn-success">Cancelar</button>
      </a>
      <button type="submit" name="excluir" class="btn btn-danger">Excluir</button>
    </div>
  </form>
</main>

arquivo /Vagas/Visoes/Footer.php
    <!-- .container -->
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>  </body>
</html>

arquivo /Vagas/Visoes/Formulario.php
<main>
<section>
  <a href="../Controles/Controle.php?inicio"><button class="btn btn-success">Voltar</button></a>
</section>
<h2 class="mt-3"><?=TITLE?></h2>
<form method="post" action='../Controles/Controle.php'>
    <div class="form-group"><label>Título</label>
      <input type="text" class="form-control" name="titulo" value="<?=$obVaga->titulo?>">
      <input type=hidden name=id value=<?=$id?>>
    </div>
    <div class="form-group"><label>Descrição</label>
      <textarea class="form-control" name="descricao" rows="5"><?=$obVaga->descricao?></textarea>
    </div>
    <div class="form-group"><label>Status</label>
      <div>
        <div class="form-check form-check-inline"><label class="form-control">
        <input type="radio" name="ativo" value="s" checked> Ativo</label>
        </div>
        <div class="form-check form-check-inline"><label class="form-control">
        <input type="radio" name="ativo" value="n" <?=$obVaga->ativo == 'n' ? 'checked' : ''?>> Inativo
        </label>
        </div>
      </div>
    </div>
    <div class="form-group"><input type="submit" class="btn btn-success mt-3">
    </div>
  </form>
</main>

arquivo /Vagas/Visoes/Header.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <title>WDEV Vagas!</title>
  </head>
  <body class="bg-dark text-light">
    <div class="container">
      <div class="jumbotron bg-danger">
        <h1>WDEV Vagas</h1>
        <p>Exemplo de CRUD com PHP orientados a objetos</p>
      </div>




arquivo /Vagas/Visoes/Listagem.php
<?php
$resultados = '';
foreach($vagas as $vaga){
    $resultados .= "<tr>
      <td>$vaga->id
      <td>$vaga->titulo
      <td>$vaga->descricao
      <td>".($vaga->ativo == 's' ? 'Ativo' : 'Inativo')."
      <td>".date('d/m/Y à\s H:i:s',strtotime($vaga->data))."
      <td>
      <a href='/Vagas/Controles/Controle.php?editar=$vaga->id'>
        <button type=button class='btn btn-primary'>Editar</button>
      </a>
      <a href='/Vagas/Controles/Controle.php?excluir=$vaga->id'>
        <button type=button class='btn btn-danger'>Excluir</button>
      </a>";}
$resultados = strlen($resultados) ? $resultados : "<tr>
      <td colspan=6 class='text-center>Nenhuma vaga encontrada";?>
<main>
  <section>
    <a href='/Vagas/Controles/Controle.php?Cadastrar'>
      <button class="btn btn-success">Nova vaga</button>
    </a>
  </section>
  <section>
    <table class="table bg-light mt-3">
    <tr><th>ID<th>Título<th>Descrição<th>Status<th>Data<th>Ações
    <?=$resultados?>
    </table>
  </section>
</main>

 

 

Captura de tela 2023-12-11 064441.png

Edited by Frank K Hosaka
Link to comment
Share on other sites

1 answer to this question

Recommended Posts

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.1k
    • Total Posts
      651.8k
×
×
  • Create New...