/
usuario_modelo.php
120 lines (91 loc) · 3.55 KB
/
usuario_modelo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
class UsuarioModelo{
private $db;
public function __CONSTRUCT(){
try{
$this->db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
die($ex->getMessage());
}
}
public function registrar(Usuario $datos){
try{
$sql = "insert into usuario (nombre, apellido, login, password)
values (?, ?, ?, ?)";
$this->db->prepare($sql)
->execute(
array(
$datos->get('nombre'),
$datos->get('apellido'),
$datos->get('login'),
$datos->get('password')
)
);
} catch (Exception $ex) {
die($ex->getMessage());
}
}
public function listar(){
try {
$listar = array();
$consulta = $this->db->prepare("select * from usuario");
$consulta->execute();
foreach ($consulta->fetchAll(PDO::FETCH_OBJ) as $resultado){
$usuario = new Usuario();
$usuario->set('id', $resultado->id);
$usuario->set('nombre', $resultado->nombre);
$usuario->set('apellido', $resultado->apellido);
$usuario->set('login', $resultado->login);
$listar[] = $usuario;
}
return $listar;
} catch (Exception $ex) {
die($ex->getMessage());
}
}
public function eliminar($id){
try {
$this->db->prepare("delete from usuario where id = ?")
->execute(array($id));
} catch (Exception $ex) {
die($ex->getMessage());
}
}
public function buscar($id){
try {
$consulta = $this->db->prepare("select * from usuario where id = ?");
$consulta->execute(array($id));
$resultado = $consulta->fetch(PDO::FETCH_OBJ);
$usuario = new Usuario();
$usuario->set('id', $resultado->id);
$usuario->set('nombre', $resultado->nombre);
$usuario->set('apellido', $resultado->apellido);
$usuario->set('login', $resultado->login);
return $usuario;
} catch (Exception $ex) {
die($ex->getMessage());
}
}
public function actualizar(Usuario $datos){
try {
$this->db->prepare("Update usuario set"
. " nombre = ?,"
. " apellido = ?,"
. " login = ?,"
. " password = ?"
. " where id = ?")
->execute(
array(
$datos->get('nombre'),
$datos->get('apellido'),
$datos->get('login'),
$datos->get('password'),
$datos->get('id')
)
);
} catch (Exception $ex) {
die($ex->getMessage());
}
}
}