DEV Community

Cover image for CRUD Simples Utilizando PHP + MySql + Bootstrap 4
Brayan Monteiro
Brayan Monteiro

Posted on

CRUD Simples Utilizando PHP + MySql + Bootstrap 4

README.md

CRUD Simples Utilizando PHP + MySql + Bootstrap 4

Cadastro Simples de Usuário Utilizando apenas PHP

Instalação

Criar a tabela no Banco de dados:

create table usuario(
    id integer primary key AUTO_INCREMENT,
    nome varchar(200) not null,
    sobrenome varchar(300) not null,
    idade integer not null,
    sexo char(1) not null
)
Enter fullscreen mode Exit fullscreen mode

Configurar o arquivo Conexao.php dentro da pasta 'app/conexao':

Adicione o codigo abaixo dentro da função getConexão(), caso seu banco seja Mysql ja está como padrão.

Lembre-se de alterar os dados(dbname,user,password) na conexão de acordo com seu banco.

-Conexão para MySql

 if (!isset(self::$instance)) {
           self::$instance = new PDO('mysql:host=localhost;dbname=github', 'root', '', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
           self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           self::$instance->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
       }

       return self::$instance;
Enter fullscreen mode Exit fullscreen mode

-Conexão para PostgreSql

        $host = 'localhost;port=5432';
        $dbname = 'github';
        $user = 'root';
        $pass = '';
        try {

            if (!isset(self::$instance)) {
                self::$instance = new \PDO('pgsql:host='.$host.';dbname=' . $dbname . ';options=\'--client_encoding=UTF8\'', $user, $pass);
                self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                self::$instance->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_EMPTY_STRING);
            }

            return self::$instance;
        } catch (Exception $ex) {
            echo $ex.'<br>';
        }
Enter fullscreen mode Exit fullscreen mode

Créditos

Brayan Monteiro

email: brayanmonteirooo@gmail.com

index.php

<?php
include_once "./app/conexao/Conexao.php";
include_once "./app/dao/UsuarioDAO.php";
include_once "./app/model/Usuario.php";

//instancia as classes
$usuario = new Usuario();
$usuariodao = new UsuarioDAO();
?>

<!DOCTYPE html>









CRUD Simples PHP

<br>
.menu,<br>
thead {<br>
background-color: #bbb !important;<br>
}</p>
<div class="highlight"><pre class="highlight plaintext"><code> .row {
padding: 10px;
}
&lt;/style&gt;
</code></pre></div>
<p></head></p>

<p><body><br>
<nav class="navbar navbar-light bg-light menu"><br>
<div class="container"><br>
<a class="navbar-brand" href="#"><br>
CRUD PHP POO<br>
</a><br>
</div><br>
</nav><br>
<div class="container"><br>
<form action="app/controller/UsuarioController.php" method="POST"><br>
<div class="row"><br>
<div class="col-md-3"><br>
<label>Nome</label><br>
<input type="text" name="nome" value="" autofocus class="form-control" require /><br>
</div><br>
<div class="col-md-5"><br>
<label>Sobrenome</label><br>
<input type="text" name="sobrenome" value="" class="form-control" require /><br>
</div><br>
<div class="col-md-2"><br>
<label>Idade</label><br>
<input type="number" name="idade" value="" class="form-control" require /><br>
</div><br>
<div class="col-md-2"><br>
<label>Sexo</label><br>
<select name="sexo" class="form-control"><br>
<option value="M">Masculino</option><br>
<option value="F">Feminino</option><br>
</select><br>
</div><br>
<div class="col-md-2"><br>
<br><br>
<button class="btn btn-primary" type="submit" name="cadastrar">Cadastrar</button><br>
</div><br>
</div><br>
</form><br>
<hr><br>
<div class="table-responsive"><br>
<table class="table table-sm table-bordered table-hover"><br>
<thead><br>
<tr><br>
<th>Id</th><br>
<th>Nome</th><br>
<th>Sobrenome</th><br>
<th>Idade</th><br>
<th>Sexo</th><br>
<th>Ações</th><br>
</tr><br>
</thead><br>
<tbody><br>
&lt;?php foreach ($usuariodao-&gt;read() as $usuario) : ?&gt;<br>
<tr><br>
<td>&lt;?= $usuario-&gt;getId() ?&gt;</td><br>
<td>&lt;?= $usuario-&gt;getNome() ?&gt;</td><br>
<td>&lt;?= $usuario-&gt;getSobrenome() ?&gt;</td><br>
<td>&lt;?= $usuario-&gt;getIdade() ?&gt;</td><br>
<td>&lt;?= $usuario-&gt;getSexo()?&gt;</td><br>
<td class="text-center"><br>
<button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#editar>&lt;?= $usuario-&gt;getId() ?&gt;&quot;&gt;<br>
Editar<br>
</button><br>
<a href="app/controller/UsuarioController.php?del=<?= $usuario->getId() ?&gt;&quot;&gt;<br>
<button class="btn btn-danger btn-sm" type="button">Excluir</button><br>
</a><br>
</td><br>
</tr><br>
&lt;!-- Modal --&gt;<br>
<div class="modal fade" id="editar>&lt;?= $usuario-&gt;getId() ?&gt;&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;exampleModalLabel&quot; aria-hidden=&quot;true&quot;&gt;<br>
<div class="modal-dialog modal-lg" role="document"><br>
<div class="modal-content"><br>
<div class="modal-header"><br>
<h5 class="modal-title" id="exampleModalLabel">Editar</h5><br>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><br>
<span aria-hidden="true">&times;</span><br>
</button><br>
</div><br>
<div class="modal-body"><br>
<form action="app/controller/UsuarioController.php" method="POST"><br>
<div class="row"><br>
<div class="col-md-5"><br>
<label>Nome</label><br>
<input type="text" name="nome" value="<?= $usuario->getNome() ?&gt;&quot; class=&quot;form-control&quot; require /&gt;<br>
</div><br>
<div class="col-md-7"><br>
<label>Sobrenome</label><br>
<input type="text" name="sobrenome" value="<?= $usuario->getSobrenome() ?&gt;&quot; class=&quot;form-control&quot; require /&gt;<br>
</div><br>
</div><br>
<div class="row"><br>
<div class="col-md-3"><br>
<label>Idade</label><br>
<input type="number" name="idade" value="<?= $usuario->getIdade() ?&gt;&quot; class=&quot;form-control&quot; require /&gt;<br>
</div><br>
<div class="col-md-3"><br>
<label>Sexo</label><br>
<select name="sexo" class="form-control"><br>
&lt;?php if ($usuario-&gt;getSexo() == &#39;F&#39;) : ?&gt;<br>
<option value="F">Feminino</option><br>
<option value="M">Masculino</option><br>
&lt;?php else : ?&gt;<br>
<option value="M">Masculino</option><br>
<option value="F">Feminino</option><br>
&lt;?php endif ?&gt;</p>
<div class="highlight"><pre class="highlight plaintext"><code> &lt;/select&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="row"&gt;
&lt;div class="col-md-2"&gt;
&lt;br&gt;
&lt;input type="hidden" name="id" value="&lt;?= $usuario-&gt;getId() ?&gt;" /&gt;
&lt;button class="btn btn-primary" type="submit" name="editar"&gt;Cadastrar&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;

                        &amp;lt;/div&amp;gt;
                    &amp;lt;/div&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;?php endforeach ?&amp;gt;
        &amp;lt;/tbody&amp;gt;
    &amp;lt;/table&amp;gt;
&amp;lt;/div&amp;gt;
Enter fullscreen mode Exit fullscreen mode

&lt;/div&gt;
&lt;script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"&gt;&lt;/script&gt;
</code></pre></div>
<p></body></p>
<h2>
<a name="" href="#" class="anchor">
</a>
</html>
</h2>
<h2>
<a name="appmodelusuariophp" href="#appmodelusuariophp" class="anchor">
</a>
/app/model/Usuario.php
</h2>

<p>&lt;?php</p>

<p>class Usuario{</p>
<div class="highlight"><pre class="highlight plaintext"><code>private $id;
private $nome;
private $sobrenome;
private $idade;
private $sexo;

function getId() {
return $this-&gt;id;
}

function getNome() {
return $this-&gt;nome;
}

function getSobrenome() {
return $this-&gt;sobrenome;
}

function getIdade() {
return $this-&gt;idade;
}

function getSexo() {
return $this-&gt;sexo;
}

function setId($id) {
$this-&gt;id = $id;
}

function setNome($nome) {
$this-&gt;nome = $nome;
}

function setSobrenome($sobrenome) {
$this-&gt;sobrenome = $sobrenome;
}

function setIdade($idade) {
$this-&gt;idade = $idade;
}

function setSexo($sexo) {
$this-&gt;sexo = $sexo;
}
</code></pre></div>
<p>}</p>

<hr>
<h2>
<a name="appdaousuariodaophp" href="#appdaousuariodaophp" class="anchor">
</a>
/app/dao/UsuarioDAO.php
</h2>

<p>&lt;?php<br>
/*<br>
Criação da classe Usuario com o CRUD<br>
*/<br>
class UsuarioDAO{</p>
<div class="highlight"><pre class="highlight plaintext"><code>public function create(Usuario $usuario) {
try {
$sql = "INSERT INTO usuario (

nome,sobrenome,idade,sexo)
VALUES (
:nome,:sobrenome,:idade,:sexo)";

    $p_sql = Conexao::getConexao()-&amp;gt;prepare($sql);
    $p_sql-&amp;gt;bindValue(":nome", $usuario-&amp;gt;getNome());
    $p_sql-&amp;gt;bindValue(":sobrenome", $usuario-&amp;gt;getSobrenome());
    $p_sql-&amp;gt;bindValue(":idade", $usuario-&amp;gt;getIdade());
    $p_sql-&amp;gt;bindValue(":sexo", $usuario-&amp;gt;getSexo());

    return $p_sql-&amp;gt;execute();
} catch (Exception $e) {
    print "Erro ao Inserir usuario &amp;lt;br&amp;gt;" . $e . '&amp;lt;br&amp;gt;';
}
Enter fullscreen mode Exit fullscreen mode

}

public function read() {
try {
$sql = "SELECT * FROM usuario order by nome asc";
$result = Conexao::getConexao()-&gt;query($sql);
$lista = $result-&gt;fetchAll(PDO::FETCH_ASSOC);
$f_lista = array();
foreach ($lista as $l) {
$f_lista[] = $this-&gt;listaUsuarios($l);
}
return $f_lista;
} catch (Exception $e) {
print "Ocorreu um erro ao tentar Buscar Todos." . $e;
}
}

public function update(Usuario $usuario) {
try {
$sql = "UPDATE usuario set

          nome=:nome,
          sobrenome=:sobrenome,
          idade=:idade,
          sexo=:sexo                  

          WHERE id = :id";
    $p_sql = Conexao::getConexao()-&amp;gt;prepare($sql);
    $p_sql-&amp;gt;bindValue(":nome", $usuario-&amp;gt;getNome());
    $p_sql-&amp;gt;bindValue(":sobrenome", $usuario-&amp;gt;getSobrenome());
    $p_sql-&amp;gt;bindValue(":idade", $usuario-&amp;gt;getIdade());
    $p_sql-&amp;gt;bindValue(":sexo", $usuario-&amp;gt;getSexo());
    $p_sql-&amp;gt;bindValue(":id", $usuario-&amp;gt;getId());
    return $p_sql-&amp;gt;execute();
} catch (Exception $e) {
    print "Ocorreu um erro ao tentar fazer Update&amp;lt;br&amp;gt; $e &amp;lt;br&amp;gt;";
}
Enter fullscreen mode Exit fullscreen mode

}

public function delete(Usuario $usuario) {
try {
$sql = "DELETE FROM usuario WHERE id = :id";
$p_sql = Conexao::getConexao()-&gt;prepare($sql);
$p_sql-&gt;bindValue(":id", $usuario-&gt;getId());
return $p_sql-&gt;execute();
} catch (Exception $e) {
echo "Erro ao Excluir usuario&lt;br&gt; $e &lt;br&gt;";
}
}

private function listaUsuarios($row) {
$usuario = new Usuario();
$usuario-&gt;setId($row['id']);
$usuario-&gt;setNome($row['nome']);
$usuario-&gt;setSobrenome($row['sobrenome']);
$usuario-&gt;setIdade($row['idade']);
$usuario-&gt;setSexo($row['sexo']);

return $usuario;
Enter fullscreen mode Exit fullscreen mode

}
</code></pre></div>
<p>}</p>
<h2>
<a name="gt" href="#gt" class="anchor">
</a>
?&gt;
</h2>
<h2>
<a name="appcontrollerusuariocontrollerphp" href="#appcontrollerusuariocontrollerphp" class="anchor">
</a>
/app/controller/UsuarioController.php
</h2>

<p>&lt;?php<br>
include_once &quot;../conexao/Conexao.php&quot;;<br>
include_once &quot;../model/Usuario.php&quot;;<br>
include_once &quot;../dao/UsuarioDAO.php&quot;;</p>

<p>//instancia as classes<br>
$usuario = new Usuario();<br>
$usuariodao = new UsuarioDAO();</p>

<p>//pega todos os dados passado por POST</p>

<p>$d = filter_input_array(INPUT_POST);</p>

<p>//se a operação for gravar entra nessa condição<br>
if(isset($_POST[&#39;cadastrar&#39;])){</p>
<div class="highlight"><pre class="highlight plaintext"><code>$usuario-&gt;setNome($d['nome']);
$usuario-&gt;setSobrenome($d['sobrenome']);
$usuario-&gt;setIdade($d['idade']);
$usuario-&gt;setSexo($d['sexo']);

$usuariodao-&gt;create($usuario);

header("Location: ../../");
</code></pre></div>
<p>} <br>
// se a requisição for editar<br>
else if(isset($_POST[&#39;editar&#39;])){</p>
<div class="highlight"><pre class="highlight plaintext"><code>$usuario-&gt;setNome($d['nome']);
$usuario-&gt;setSobrenome($d['sobrenome']);
$usuario-&gt;setIdade($d['idade']);
$usuario-&gt;setSexo($d['sexo']);
$usuario-&gt;setId($d['id']);

$usuariodao-&gt;update($usuario);

header("Location: ../../");
</code></pre></div>
<p>}<br>
// se a requisição for deletar<br>
else if(isset($_GET[&#39;del&#39;])){</p>
<div class="highlight"><pre class="highlight plaintext"><code>$usuario-&gt;setId($_GET['del']);

$usuariodao-&gt;delete($usuario);

header("Location: ../../");
</code></pre></div>
<p>}else{<br>
header(&quot;Location: ../../&quot;);</p>
<h2>
<a name="" href="#" class="anchor">
</a>
}
</h2>
<h2>
<a name="appconexaoconexaophp" href="#appconexaoconexaophp" class="anchor">
</a>
/app/conexao/Conexao.php
</h2>

<p>&lt;?php<br>
class Conexao {</p>

<p>public static $instance;</p>

<p>private function __construct() {<br>
//<br>
}</p>

<p>public static function getConexao() {<br>
if (!isset(self::$instance)) {<br>
self::$instance = new PDO(&#39;mysql:host=localhost;dbname=crud_example&#39;, &#39;root&#39;, &#39;&#39;, array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; &quot;SET NAMES utf8&quot;));<br>
self::$instance-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br>
self::$instance-&gt;setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);<br>
}</p>
<div class="highlight"><pre class="highlight plaintext"><code> return self::$instance;
</code></pre></div>
<p>}</p>

<p>}</p>

Top comments (0)