1 | <?php |
||
2 | |||
3 | /* |
||
4 | * This file is part of the Ocrend Framewok 3 package. |
||
5 | * |
||
6 | * (c) Ocrend Software <[email protected]> |
||
7 | * |
||
8 | * For the full copyright and license information, please view the LICENSE |
||
9 | * file that was distributed with this source code. |
||
10 | */ |
||
11 | |||
12 | namespace Ocrend\Kernel\Database\Drivers\Mysql; |
||
13 | |||
14 | use Ocrend\Kernel\Database\Driver; |
||
15 | |||
16 | /** |
||
17 | * Driver de conexión con Mysql utilizando mysqli |
||
18 | * |
||
19 | * @author Brayan Narváez <[email protected]> |
||
20 | */ |
||
21 | class Mysql extends \mysqli implements Driver { |
||
22 | |||
23 | /** |
||
24 | * Constructor de la clase |
||
25 | */ |
||
26 | public function __construct() { |
||
27 | global $config; |
||
28 | |||
29 | # Configuración |
||
30 | $mysqli = $config['database']['drivers']['mysql']; |
||
31 | |||
32 | # Puerto y socket por defecto |
||
33 | $port = ini_get('mysqli.default_port'); |
||
34 | $socket = ini_get('mysqli.default_socket'); |
||
35 | |||
36 | # Conexión |
||
37 | parent::__construct( |
||
38 | $mysqli['host'], |
||
39 | $mysqli['user'], |
||
40 | $mysqli['pass'], |
||
41 | $mysqli['name'], |
||
42 | $mysqli['port'] == 'default' ? $port : $mysqli['port'], |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
43 | $mysqli['socket'] == 'default' ? $socket : $mysqli['socket'] |
||
44 | ); |
||
45 | |||
46 | # Verificar conexión |
||
47 | if($this->connect_errno) { |
||
48 | throw new \RuntimeException('ERROR :' . $this->connect_errno . ' conectando con la base de datos' . $this->connect_error); |
||
49 | } |
||
50 | |||
51 | # Cambiar caracteres |
||
52 | $this->set_charset("utf8mb4"); |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * Escapa caracteres para evitar sql injection |
||
57 | * |
||
58 | * @param string $param : Parámetro |
||
59 | * |
||
60 | * @return string escapado |
||
61 | */ |
||
62 | public function scape($param) : string { |
||
63 | return $this->real_escape_string($param); |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * Selecciona elementos de una tabla y devuelve un objeto |
||
68 | * |
||
69 | * @param string $fields: Campos |
||
70 | * @param string $table: Tabla |
||
71 | * @param null|string $inners: Inners |
||
72 | * @param null|string $where : Condiciones |
||
73 | * @param null|int $limit: Límite de resultados |
||
74 | * @param string $extra: Instrucciones extras |
||
75 | * |
||
76 | * @return bool|stdClass |
||
0 ignored issues
–
show
|
|||
77 | */ |
||
78 | public function select(string $fields, string $table, $inners = null, $where = null, $limit = null, string $extra = '') { |
||
79 | $result = $this->query("SELECT $fields FROM $table $inners " |
||
80 | . (null != $where ? "WHERE $where" : '') |
||
0 ignored issues
–
show
|
|||
81 | . " $extra " |
||
82 | . (null !== $limit ? "LIMIT $limit" : '') |
||
83 | ); |
||
84 | |||
85 | if(false != $result && $result->num_rows) { |
||
86 | $matriz = (array) $result->fetch_all(MYSQLI_ASSOC); |
||
87 | $result->free(); |
||
88 | |||
89 | return $matriz; |
||
0 ignored issues
–
show
|
|||
90 | } |
||
91 | |||
92 | return false; |
||
93 | } |
||
94 | |||
95 | /** |
||
96 | * Actualiza elementos de una tabla en la base de datos según una condición |
||
97 | * |
||
98 | * @param string $table: Tabla a actualizar |
||
99 | * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
||
100 | * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
||
101 | * @param null|string $where: Condición que indica quienes serán modificados |
||
102 | * @param null|string $limite: Límite de elementos modificados, por defecto los modifica a todos |
||
103 | * |
||
104 | * @throws \RuntimeException si el arreglo está vacío |
||
105 | * @return int con la cantidad de tablas afectadas |
||
106 | */ |
||
107 | public function update(string $table, array $e, $where = null, $limit = null) : int { |
||
108 | if (sizeof($e) == 0) { |
||
109 | throw new \RuntimeException('El arreglo pasado por $this->db->update(\'' . $table . '\'...) está vacío.'); |
||
110 | } |
||
111 | |||
112 | $query = "UPDATE $table SET "; |
||
113 | foreach ($e as $campo => $valor) { |
||
114 | $query .= $campo . '=\'' . $this->scape($valor) . '\','; |
||
115 | } |
||
116 | $query[strlen($query) - 1] = ' '; |
||
117 | |||
118 | $this->real_query($query |
||
119 | . (null != $where ? "WHERE $where" : '') |
||
120 | . (null !== $limit ? "LIMIT $limit" : '') |
||
121 | ); |
||
122 | |||
123 | return $this->affected_rows; |
||
124 | } |
||
125 | |||
126 | /** |
||
127 | * Inserta una serie de elementos a una tabla en la base de datos |
||
128 | * |
||
129 | * @param string $table: Tabla a la cual se le va a insertar elementos |
||
130 | * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
||
131 | * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
||
132 | * |
||
133 | * @throws \RuntimeException si el arreglo está vacío |
||
134 | * |
||
135 | * @return int con el PRIMARY AUTO_INCREMENT de el último elemento insertado |
||
136 | */ |
||
137 | public function insert(string $table, array $e) : int { |
||
138 | if (sizeof($e) == 0) { |
||
139 | throw new \RuntimeException('El arreglo pasado por $this->db->insert(\'' . $table . '\',...) está vacío.'); |
||
140 | } |
||
141 | |||
142 | $query = "INSERT INTO $table ("; |
||
143 | $values = ''; |
||
144 | foreach ($e as $campo => $v) { |
||
145 | $query .= $campo . ','; |
||
146 | $values .= '\'' . $this->scape($v) . '\','; |
||
147 | } |
||
148 | $query[strlen($query) - 1] = ')'; |
||
149 | $values[strlen($values) - 1] = ')'; |
||
150 | $query .= ' VALUES (' . $values . ';'; |
||
151 | |||
152 | $this->real_query($query); |
||
153 | |||
154 | return $this->insert_id; |
||
155 | } |
||
156 | |||
157 | /** |
||
158 | * Elimina elementos de una tabla y devuelve la cantidad de filas afectadas |
||
159 | * |
||
160 | * @param string $table: Tabla a la cual se le quiere remover un elemento |
||
161 | * @param null|string $where: Condición de borrado que define quien/quienes son dichos elementos |
||
162 | * @param null|string $limit: Por defecto se limita a borrar un solo elemento que cumpla el $where |
||
163 | * |
||
164 | * @return int cantidad de filas afectadas |
||
165 | */ |
||
166 | public function delete(string $table, $where = null, $limit = null) : int { |
||
167 | $this->real_query("DELETE FROM $table " . (null != $where ? "WHERE $where" : ' ') . (null !== $limit ? "LIMIT $limit" : '')); |
||
168 | |||
169 | return $this->affected_rows; |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * Destructor de la clase |
||
174 | */ |
||
175 | public function __destruct() { |
||
176 | $this->close(); |
||
177 | } |
||
178 | |||
179 | } |
||
180 |