I am trying to develop a function that will help me simplify my database queries. I am implementing it with prepared queries and a bit of dynamism at the moment of knowing that I am executing. Actually I have never used the prepared queries nor have I used mysqli
for objects (I have always done it by procedures, for example mysqli_query()
) The code I already documented then I do not think there is so much problem in explaining what it does. I have a problem that says the following
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt :: fetch_assoc () in /fakepath/QueryEngine.php:80
Again, I have never used this procedure, you may find the error obvious.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class QueryEngine {
protected $conn;
public function __construct(){
$server = 'localjost';
$user = 'iuser';
$pass = 'pasuord';
$db = 'deirabeis';
$this->conn = new mysqli( $server, $user, $pass, $db );
}
public function executeQuery( $query, $params, $type, $meta = false ){
//Preparamos dos arreglos que servirán para retornar y almacenar parametros
$result = array();
$data = array();
//Separamos la consulta y los tipos de datos que se enviaran
$order_arr = explode( ' ', $query );
$type_arr = explode( ',', $type );
//La orden será la primera detección (select, update, insert)
$order = strtolower( $order_arr[0] );
//Validamos si hay errores en la conexión y creamos un arreglo asociativo
//Si está la meta activa se añade información extra
if( $this->conn->connect_errno ){
$result['data'] = null;
$result['message'] = "Falló la conexión a la base de datos";
if( $meta ){
$result['meta']['query'] = $query;
$result['meta']['params'] = implode( ',', $params );
$result['meta']['error'] = $this->conn->connect_errno . ' ' . '('.$this->conn->connect_error.')';
}
}
else{
//Añadimos la codificación de los datos
$this->conn->set_charset( 'utf-8' );
//Validamos que se haya preparado bien la consulta y creamos el arreglo
if( !$stmt = $this->conn->prepare( $query ) ){
$result['data'] = null;
$result['message'] = "Consulta mal formada";
if( $meta ){
$result['meta']['query'] = $query;
$result['meta']['params'] = implode( ',', $params );
$result['meta']['error'] = $this->conn->errno . " " . $this->conn->error;
}
}
else{
//Ciclamos los parámetros, los limpiamos y los agregamos al arreglo $data
foreach( $params as $param ){
array_push( $data, $this->conn->real_escape_string($param) );
}
//Ligamos los parámetros y su respectivo tipo de dato al statement
for ( $i = 0; $i < count( $data ); $i++ ) {
$stmt->bind_param( $type_arr[ $i ], $data[ $i ] );
}
//Validamos la ejecución de la consulta
if( !$stmt->execute() ){
$result['data'] = null;
$result['message'] = "Consulta mal formada";
if( $meta ){
$result['meta']['query'] = $query;
$result['meta']['params'] = implode( ',', $params );
$result['meta']['error'] = $this->conn->errno . " " . $this->conn->error;
}
}
else{
//Según cual sea la sentencia se ejecutarán diferentes acciones
switch ( $order ) {
case 'select':
//Almacenamos la información
$stmt->store_result();
$x = 0;
//Barremos los resultados
while ( $row = $stmt->fetch_assoc() ) {
$data[ $x ] = $row;
$x++;
}
$result['data'] = $data;
$result['message'] = "Consulta exitosa";
if( $meta ){
$result['meta']['query'] = $query;
$result['meta']['params'] = implode( ',', $params );
$result['meta']['error'] = 'No error';
}
//Liberamos la memoria
$stmt->free_result();
break;
case 'insert':
break;
case 'update':
break;
default:
$result['data'] = null;
$result['message'] = "No es posible ejecutar esta acción";
if( $meta ){
$result['meta']['query'] = $query;
$result['meta']['params'] = implode( ',', $params );
$result['meta']['error'] = 'Sentencia ' . $oder . ' no reconocida';
}
break;
}
}
//Cerramos la conexión
$stmt->close();
}
}
//Retornamos el resultado
return $result;
}
}
?>
I am invoking the method in the following way:
include 'QueryEngine.php';
$queryBuilder = new QueryEngine();
$query = "SELECT * FROM USERS";
$params = array();
$values = '';
$result = $queryBuilder->executeQuery( $query, $params, $values, 1 );
print_r( $result );