Skip to content

Instantly share code, notes, and snippets.

@Simplesmente
Created October 17, 2016 23:03
Show Gist options
  • Save Simplesmente/2b27edb043b294f273463692af69eaf0 to your computer and use it in GitHub Desktop.
Save Simplesmente/2b27edb043b294f273463692af69eaf0 to your computer and use it in GitHub Desktop.
Classe Usuário
<?php
class Usuarios {
private $db;
public function __construct() {
try {
// TROCAR DOS PARAMETROS ABAIXO PARA O DO SEU BANCO
$this->db = new PDO("mysql:dbname=code_dbal;host=localhost", "root", "");
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "FALHA: ".$e->getMessage();
}
}
public function selecionar($id) {
$sql = $this->db->prepare("SELECT * FROM usuarios WHERE id = :id");
$sql->bindValue(":id", $id);
$sql->execute();
$array = array();
if($sql->rowCount() > 0) {
$array = $sql->fetch();
}
return $array;
}
/**
* @param array $data data user
* @return bool return true if data have been inserted in database
*/
public function inserir(array $data) {
if( $this->validator($data) ){
$sql = "INSERT INTO usuarios SET nome = :nome, email = :email, senha = :senha";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(":nome",$data['nome']);
$stmt->bindParam(":email", $data['email']);
$stmt->bindValue(":senha", md5($data['email']));
if(!$stmt->execute()){
return ['message' => 'Erro to insert data'];
}
return $this->db->lastInsertId(); // return ultimo ID inserido no banco.
return $stmt->execute(); // return true se chegar até aqui.
}
}
public function atualizar($nome, $email, $senha, $id) {
$sql = $this->db->prepare("UPDATE usuarios SET nome = ?, email = ?, senha = ? WHERE id = ?");
$sql->execute(array($nome, $email, md5($senha), $id));
}
public function excluir($id) {
$sql = $this->db->prepare("DELETE FROM usuarios WHERE id = ?");
$sql->bindValue(1, $id);
$sql->execute();
}
private function validator(array $data){
$errors ='';
foreach ($data as $key => $value) {
if(empty($value)){
$errors[$key] = "{$key} is required";
}
}
if($errors){
return ['message' => $errors];
}
return true;
}
}
// ARQUIVO INDEX.PHP
ini_set('display_errors',1);
require 'usuarios.php';
$u = new Usuarios();
$usuario = ['nome' => 'Mary Doe',
'email' => '[email protected]',
'senha' => '123'];
print_r( $u->inserir($usuario)); // retornar ultimo ID inserido
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment