Home Database Mysql Tutorial Simple CRUD Using PHP MySql Bootstrap 4

Simple CRUD Using PHP MySql Bootstrap 4

Dec 18, 2024 am 11:33 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

How do you represent relationships using foreign keys? How do you represent relationships using foreign keys? Mar 19, 2025 pm 03:48 PM

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

How do you create indexes on JSON columns? How do you create indexes on JSON columns? Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

See all articles
Id Nome Sobrenome Idade Sexo Ações
getId() ?> getNome() ?> getSobrenome() ?> getIdade() ?> getSexo()?>