Ver Mensaje Individual
  #2 (permalink)  
Antiguo 19/08/2015, 23:03
Avatar de NSD
NSD
Colaborador
 
Fecha de Ingreso: mayo-2012
Ubicación: Somewhere
Mensajes: 1.332
Antigüedad: 12 años
Puntos: 320
Respuesta: Corregir/mejorar mi código

Lo que intentas hacer es una DBAL, busca en google con ese termino y veras muchas soluciones.

Esta desactualizado, pero esta es una clase que hice hace bastante para tal fin.

Con respecto a tu código, yo lo haría así:
DbTable.php
Código PHP:
Ver original
  1. <?php
  2. class DbTable {
  3.    
  4.     const ERROR_CONNECTION = "No se pudo conectar a la base de datos.";
  5.     const ERROR_PREPARE_STMT = "Error %1\$n preparando la sentencia. %2\$s.";
  6.     const ERROR_BIND_PARAM = "Error al agregar los parametros a la sentencia.";
  7.     const ERROR_EXECUTE_STMT = "Error %1\$n ejecutando la sentencia. %2\$s.";
  8.    
  9.     private static $_instance;
  10.     private $_table;
  11.     private $_stmt;
  12.     public $props = [];
  13.    
  14.     public function __construct($table) {
  15.         if(is_null(self::$_instance)) {
  16.             self::$_instance = new mysqli("localhost", "root", "", "database");
  17.             if(self::$_instance->connect_errno)
  18.                 throw new Exception(self::ERROR_CONNECTION);
  19.             else
  20.                 self::$_instance->set_charset("utf8");
  21.         }
  22.        
  23.         $this->_table = $table;
  24.     }
  25.    
  26.     public function flush() {
  27.         if(!is_null($this->_stmt)) {
  28.             $this->_stmt->close();
  29.             $this->_stmt = null;
  30.         }
  31.         $this->props = [];
  32.        
  33.         return $this;
  34.     }
  35.    
  36.     public function insert() {
  37.         $this->exec("INSERT INTO ".$this->_table." (".implode(array_keys($this->props)).") VALUES (?".str_repeat(",?", count($this->props)-1).");", $this->props);
  38.        
  39.         return self::$_instance->insert_id;
  40.     }
  41.    
  42.     public function exec($query = "", $params = []) {
  43.         if(is_null($this->_stmt)) {
  44.             if(!($this->_stmt = self::$_instance->prepare($query)))
  45.                 throw new Exception(sprintf(self::ERROR_PREPARE_STMT, self::$_instance->errno, self::$_instance->error));
  46.             elseif($params) {
  47.                 $bind_params = array("");
  48.                 foreach($params as &$param) {
  49.                     switch(gettype($param)) {
  50.                         case "integer": case "boolean": $bind_params[0] .= "i"; break;
  51.                         case "double" : $bind_params[0] .= "d"; break;
  52.                         case "blob"   : $bind_params[0] .= "b"; break;
  53.                         default       : $bind_params[0] .= "s"; break;
  54.                     }
  55.                     $bind_params[] = &$param;
  56.                 }
  57.                 if(!call_user_func_array(array($this->_stmt, "bind_param"), $bind_params))
  58.                     throw new Exception(self::ERROR_BIND_PARAM);
  59.             }
  60.         }
  61.        
  62.         if(!$this->_stmt->execute())
  63.             throw new Exception(sprintf(self::ERROR_EXECUTE_STMT, self::$_instance->error, self::$_instance->errno));
  64.         else {
  65.             $result = [];
  66.             if($registros = $this->_stmt->get_result()) {
  67.                 while($registro = $registros->fetch_array(MYSQLI_ASSOC))
  68.                     $result[] = $registro;
  69.             }
  70.         }
  71.        
  72.         return $result;
  73.     }
  74. }

Uso:
Código PHP:
Ver original
  1. require("DbTable.php");
  2. try {
  3.     $usuarios = new DbTable("usuarios");
  4.     $usuarios->props["cliente"] = "Manolito";
  5.     $usuarios->props["email"] = "[email protected]";
  6.     $usuarios->props["password"] = "1234";
  7.     $usuarios->props["edad"] = 22;
  8.  
  9.     echo "Se inserto el registro: ".$insert->insert();
  10. } catch(Exception $e) {
  11.     echo "Error: " . $e->getMessage();
  12.     exit();
  13. }
__________________
Maratón de desafíos PHP Junio - Agosto 2015 en FDW | Reglamento - Desafios