Home > Database > Mysql Tutorial > Simple CRUD Using PHP MySql Bootstrap 4

Simple CRUD Using PHP MySql Bootstrap 4

DDD
Release: 2024-12-18 11:33:10
Original
748 people have browsed it

CRUD Simples Utilizando PHP   MySql   Bootstrap 4

README.md

Simple CRUD Using PHP MySql Bootstrap 4

Simple User Registration Using Just PHP

Installation

Create the table in the Database:

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
)
Copy after login
Copy after login
Copy after login

Configure the Conexao.php file within the 'app/conexao' folder:

Add the code below within the getConexão() function, if your database is Mysql it is already the default.

Remember to change the data (dbname, user, password) in the connection according to your bank.

-Connection to 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;
Copy after login
Copy after login

-Connection to 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>';
        }
Copy after login
Copy after login

Credits

Brayan Monteiro

email: brayanmonteirooo@gmail.com

index.php

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

//instantiates classes
$user = new User();
$usuariodao = new UsuarioDAO();
?>










CRUD Simple PHP



.menu,

thead {

background-color: #bbb !important;

}


padding: 10px;
}
































































read() as $usuario) : ?>



























/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)";

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
)
Copy after login
Copy after login
Copy after login

}

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

 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;
Copy after login
Copy after login

}

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']);

        $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>';
        }
Copy after login
Copy after login

}


}




?>




/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);

}



}

}

The above is the detailed content of Simple CRUD Using PHP MySql Bootstrap 4. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Id Nome Sobrenome Idade Sexo Ações
getId() ?> getNome() ?> getSobrenome() ?> getIdade() ?> getSexo()?>