/app/model/Usuario.php

class Usuario{


private $nome;
private $sobrenome;
private $idade;
private $sexo;

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

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

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

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

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

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

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

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

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

function setSexo($sexo) {
$this->sexo = $sexo;
}


}





/app/dao/UsuarioDAO.php


/*

Criação da classe Usuario com o CRUD

*/

class UsuarioDAO{


try {
$sql = \\\"INSERT INTO usuario (

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

    $p_sql = Conexao::getConexao()->prepare($sql);    $p_sql->bindValue(\\\":nome\\\", $usuario->getNome());    $p_sql->bindValue(\\\":sobrenome\\\", $usuario->getSobrenome());    $p_sql->bindValue(\\\":idade\\\", $usuario->getIdade());    $p_sql->bindValue(\\\":sexo\\\", $usuario->getSexo());    return $p_sql->execute();} catch (Exception $e) {    print \\\"Erro ao Inserir usuario <br>\\\" . $e . \\'<br>\\';}

}

public function read() {
try {
$sql = \\\"SELECT * FROM usuario order by nome asc\\\";
$result = Conexao::getConexao()->query($sql);
$lista = $result->fetchAll(PDO::FETCH_ASSOC);
$f_lista = array();
foreach ($lista as $l) {
$f_lista[] = $this->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()->prepare($sql);    $p_sql->bindValue(\\\":nome\\\", $usuario->getNome());    $p_sql->bindValue(\\\":sobrenome\\\", $usuario->getSobrenome());    $p_sql->bindValue(\\\":idade\\\", $usuario->getIdade());    $p_sql->bindValue(\\\":sexo\\\", $usuario->getSexo());    $p_sql->bindValue(\\\":id\\\", $usuario->getId());    return $p_sql->execute();} catch (Exception $e) {    print \\\"Ocorreu um erro ao tentar fazer Update<br> $e <br>\\\";}

}

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

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

return $usuario;

}


}




?>




/app/controller/UsuarioController.php


include_once \\\"../conexao/Conexao.php\\\";

include_once \\\"../model/Usuario.php\\\";

include_once \\\"../dao/UsuarioDAO.php\\\";

//instancia as classes

$usuario = new Usuario();

$usuariodao = new UsuarioDAO();

//pega todos os dados passado por POST

$d = filter_input_array(INPUT_POST);

//se a operação for gravar entra nessa condição

if(isset($_POST['cadastrar'])){


$usuario->setSobrenome($d[\\'sobrenome\\']);
$usuario->setIdade($d[\\'idade\\']);
$usuario->setSexo($d[\\'sexo\\']);

$usuariodao->create($usuario);

header(\\\"Location: ../../\\\");


}

// se a requisição for editar

else if(isset($_POST['editar'])){


$usuario->setSobrenome($d[\\'sobrenome\\']);
$usuario->setIdade($d[\\'idade\\']);
$usuario->setSexo($d[\\'sexo\\']);
$usuario->setId($d[\\'id\\']);

$usuariodao->update($usuario);

header(\\\"Location: ../../\\\");


}

// se a requisição for deletar

else if(isset($_GET['del'])){


$usuariodao->delete($usuario);

header(\\\"Location: ../../\\\");


}else{

header(\\\"Location: ../../\\\");




}




/app/conexao/Conexao.php


class Conexao {

public static $instance;

private function __construct() {

//

}

public static function getConexao() {

if (!isset(self::$instance)) {

self::$instance = new PDO('mysql:host=localhost;dbname=crud_example', '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);

}



}

}

","image":"http://www.luping.net/uploads/20250322/174263796467de8b8cb0287.jpg174263796467de8b8cb028d.jpg","datePublished":"2025-03-22T20:00:11+08:00","dateModified":"2025-03-22T20:00:11+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Simple crud using pHP + MySQL + Bootstrap 4

Simple crud using pHP + MySQL + Bootstrap 4

Posted on 2025-03-22
Browse:957

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
)

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;

-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.'
'; }

Créditos

Brayan Monteiro

email: [email protected]

index.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();
?>










CRUD Simples PHP



.menu,

thead {

background-color: #bbb !important;

}
padding: 10px;
}
</style>



Release Statement This article is reproduced at: https://dev.to/brayanmonteiroo/crud-simples-utilizando-php-mysql-bootstrap-4-m4a?1 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3