Función de declaración MySQLI personalizada para variables de encuadernación -- php campo con mysqli camp codereview Relacionados El problema

Custom MySQLi statement function for binding variables


0
vote

problema

Español

Tengo las siguientes funciones:

  <?php namespace SmallFrylib; /**  * Description of AppController  *  * @author nlubin  */ class AppController {      private $pageOn;     protected $name = __CLASS__;     protected $helpers = array();     protected $validate = array();     protected $posts = array();     protected $session;     protected $validator;     protected $template;     protected $CONFIG;      /**      *      * @param SessionManager $SESSION      * @param Config $CONFIG      * @param MySQL_Interface $firstHandle      * @param MySQL_Interface $secondHandle       */     public function __construct(SessionManager $SESSION, Config $CONFIG, MySQL_Interface $firstHandle, MySQL_Interface $secondHandle = null) {          $this->CONFIG = $CONFIG;         $this->pageOn = $this->CONFIG->get('page');         $this->session = $SESSION;         $model_name = isset($this->modelName) ? $this->modelName : $this->name;      /* Build the AppModel */         $this->$model_name = &AppModelFactory::buildModel($model_name, $CONFIG, $firstHandle, $secondHandle);      /* Get all posts */         $this->posts = $this->$model_name->getPosts();          $this->CONFIG->set('view', strtolower($model_name));          if(!$this->session->get(strtolower($model_name))){             $this->session->set(strtolower($model_name), array());         }      }      private function getPublicMethods(){         $methods = array();         $r = new ReflectionObject($this);         $r_methods = $r->getMethods(ReflectionMethod::IS_PUBLIC);         $notAllowedMethods = array("__construct", "init", "__destruct"); //list of methods that CANNOT be a view and are `keywords`         foreach($r_methods as $method){             if($method->class !== 'SmallFrylibAppController' && !in_array($method->name, $notAllowedMethods)){                  //get only public methods from extended class                 $methods[] = $method->name;             }         }         return $methods;     }      /**      *      * @param Template $TEMPLATE       */     public function setTemplate(Template $TEMPLATE){         $this->template = $TEMPLATE;         $this->setHelpers();     }      /**      * Function to run before the constructor's view function      */     public function init(){} //function to run right after constructor      /**      * Show the current page in the browser      *      * @param array $args      * @return string       */     public function displayPage($args)  {         $this->CONFIG->set('method', $this->pageOn);         $public_methods = $this->getPublicMethods();         if(in_array($this->pageOn, $public_methods))    {               call_user_func_array(array($this, $this->pageOn), $args);         }         else    {             if(!in_array($this->pageOn, $public_methods))   {                 header("HTTP/1.1 404 Not Found");             }             else {                 $this->CONFIG->set('method', '../missingfunction'); //don't even allow trying the page                 return($this->getErrorPage($this->CONFIG->get('view')."/{$this->pageOn} does not exist."));             }             exit;         }     }      /**      *      * @return string       */     function index() {}      /**      *      * @param string $msg      * @return string       */     protected function getErrorPage($msg = null)    {         $err = '<div class="error errors">%s</div>';         return sprintf($err, $msg);     }      protected function setHelpers(){         $helpers = array();         foreach($this->helpers as $helper){             $help = "{$helper}Helper";             $nameSpacedHelper = "SmallFry\helper\$help";             if(class_exists($nameSpacedHelper) && is_subclass_of($nameSpacedHelper, 'SmallFry\helper\Helper')){                 $this->$helper = new $nameSpacedHelper();                 $helpers[$helper] = $this->$helper;             }         }         $this->template->set('helpers', (object) $helpers);     }      protected function logout(){         session_destroy();         header('Location: '.WEBROOT.'index.php');         exit;     }      /**      *      * @param array $validate      * @param array $values      * @param boolean $exit      * @return boolean       */     protected function validateForm($validate = null, $values = null, $exit = true){          $this->validator = new FormValidator(); //create new validator          if($validate == null){             $validate = $this->validate;         }          foreach($validate as $field => $rules){             foreach($rules as $validate=>$message){                 $this->validator->addValidation($field, $validate, $message);             }         }          return $this->doValidate($values, $exit);     }      protected function doValidate($values = null, $exit = true){         if(!(!isset($_POST) || count($_POST) == 0)){             //some form was submitted             if(!$this->validator->ValidateForm($values)){                 $error = '';                 $error_hash = $this->validator->GetErrors();                 foreach($error_hash as $inpname => $inp_err)                 {                   $error .= $inp_err.PHP_EOL;                 }                 return $this->makeError($error, $exit);                             }         }         return true;     }      protected function makeError($str, $exit = true){         $return = $this->getErrorPage(nl2br($str));         if($exit) exit($return);         return $return;     }      protected function killPage(){ //Throw a 404 for the page         header("HTTP/1.1 404 Not Found");         exit;     } } 3  

Su principal objetivo es ahorrar tiempo al ejecutar consultas a la base de datos. El uso es el siguiente:

  <?php namespace SmallFrylib; /**  * Description of AppController  *  * @author nlubin  */ class AppController {      private $pageOn;     protected $name = __CLASS__;     protected $helpers = array();     protected $validate = array();     protected $posts = array();     protected $session;     protected $validator;     protected $template;     protected $CONFIG;      /**      *      * @param SessionManager $SESSION      * @param Config $CONFIG      * @param MySQL_Interface $firstHandle      * @param MySQL_Interface $secondHandle       */     public function __construct(SessionManager $SESSION, Config $CONFIG, MySQL_Interface $firstHandle, MySQL_Interface $secondHandle = null) {          $this->CONFIG = $CONFIG;         $this->pageOn = $this->CONFIG->get('page');         $this->session = $SESSION;         $model_name = isset($this->modelName) ? $this->modelName : $this->name;      /* Build the AppModel */         $this->$model_name = &AppModelFactory::buildModel($model_name, $CONFIG, $firstHandle, $secondHandle);      /* Get all posts */         $this->posts = $this->$model_name->getPosts();          $this->CONFIG->set('view', strtolower($model_name));          if(!$this->session->get(strtolower($model_name))){             $this->session->set(strtolower($model_name), array());         }      }      private function getPublicMethods(){         $methods = array();         $r = new ReflectionObject($this);         $r_methods = $r->getMethods(ReflectionMethod::IS_PUBLIC);         $notAllowedMethods = array("__construct", "init", "__destruct"); //list of methods that CANNOT be a view and are `keywords`         foreach($r_methods as $method){             if($method->class !== 'SmallFrylibAppController' && !in_array($method->name, $notAllowedMethods)){                  //get only public methods from extended class                 $methods[] = $method->name;             }         }         return $methods;     }      /**      *      * @param Template $TEMPLATE       */     public function setTemplate(Template $TEMPLATE){         $this->template = $TEMPLATE;         $this->setHelpers();     }      /**      * Function to run before the constructor's view function      */     public function init(){} //function to run right after constructor      /**      * Show the current page in the browser      *      * @param array $args      * @return string       */     public function displayPage($args)  {         $this->CONFIG->set('method', $this->pageOn);         $public_methods = $this->getPublicMethods();         if(in_array($this->pageOn, $public_methods))    {               call_user_func_array(array($this, $this->pageOn), $args);         }         else    {             if(!in_array($this->pageOn, $public_methods))   {                 header("HTTP/1.1 404 Not Found");             }             else {                 $this->CONFIG->set('method', '../missingfunction'); //don't even allow trying the page                 return($this->getErrorPage($this->CONFIG->get('view')."/{$this->pageOn} does not exist."));             }             exit;         }     }      /**      *      * @return string       */     function index() {}      /**      *      * @param string $msg      * @return string       */     protected function getErrorPage($msg = null)    {         $err = '<div class="error errors">%s</div>';         return sprintf($err, $msg);     }      protected function setHelpers(){         $helpers = array();         foreach($this->helpers as $helper){             $help = "{$helper}Helper";             $nameSpacedHelper = "SmallFry\helper\$help";             if(class_exists($nameSpacedHelper) && is_subclass_of($nameSpacedHelper, 'SmallFry\helper\Helper')){                 $this->$helper = new $nameSpacedHelper();                 $helpers[$helper] = $this->$helper;             }         }         $this->template->set('helpers', (object) $helpers);     }      protected function logout(){         session_destroy();         header('Location: '.WEBROOT.'index.php');         exit;     }      /**      *      * @param array $validate      * @param array $values      * @param boolean $exit      * @return boolean       */     protected function validateForm($validate = null, $values = null, $exit = true){          $this->validator = new FormValidator(); //create new validator          if($validate == null){             $validate = $this->validate;         }          foreach($validate as $field => $rules){             foreach($rules as $validate=>$message){                 $this->validator->addValidation($field, $validate, $message);             }         }          return $this->doValidate($values, $exit);     }      protected function doValidate($values = null, $exit = true){         if(!(!isset($_POST) || count($_POST) == 0)){             //some form was submitted             if(!$this->validator->ValidateForm($values)){                 $error = '';                 $error_hash = $this->validator->GetErrors();                 foreach($error_hash as $inpname => $inp_err)                 {                   $error .= $inp_err.PHP_EOL;                 }                 return $this->makeError($error, $exit);                             }         }         return true;     }      protected function makeError($str, $exit = true){         $return = $this->getErrorPage(nl2br($str));         if($exit) exit($return);         return $return;     }      protected function killPage(){ //Throw a 404 for the page         header("HTTP/1.1 404 Not Found");         exit;     } } 4  

cuando necesito ejecutar una consulta simple:

  <?php namespace SmallFrylib; /**  * Description of AppController  *  * @author nlubin  */ class AppController {      private $pageOn;     protected $name = __CLASS__;     protected $helpers = array();     protected $validate = array();     protected $posts = array();     protected $session;     protected $validator;     protected $template;     protected $CONFIG;      /**      *      * @param SessionManager $SESSION      * @param Config $CONFIG      * @param MySQL_Interface $firstHandle      * @param MySQL_Interface $secondHandle       */     public function __construct(SessionManager $SESSION, Config $CONFIG, MySQL_Interface $firstHandle, MySQL_Interface $secondHandle = null) {          $this->CONFIG = $CONFIG;         $this->pageOn = $this->CONFIG->get('page');         $this->session = $SESSION;         $model_name = isset($this->modelName) ? $this->modelName : $this->name;      /* Build the AppModel */         $this->$model_name = &AppModelFactory::buildModel($model_name, $CONFIG, $firstHandle, $secondHandle);      /* Get all posts */         $this->posts = $this->$model_name->getPosts();          $this->CONFIG->set('view', strtolower($model_name));          if(!$this->session->get(strtolower($model_name))){             $this->session->set(strtolower($model_name), array());         }      }      private function getPublicMethods(){         $methods = array();         $r = new ReflectionObject($this);         $r_methods = $r->getMethods(ReflectionMethod::IS_PUBLIC);         $notAllowedMethods = array("__construct", "init", "__destruct"); //list of methods that CANNOT be a view and are `keywords`         foreach($r_methods as $method){             if($method->class !== 'SmallFrylibAppController' && !in_array($method->name, $notAllowedMethods)){                  //get only public methods from extended class                 $methods[] = $method->name;             }         }         return $methods;     }      /**      *      * @param Template $TEMPLATE       */     public function setTemplate(Template $TEMPLATE){         $this->template = $TEMPLATE;         $this->setHelpers();     }      /**      * Function to run before the constructor's view function      */     public function init(){} //function to run right after constructor      /**      * Show the current page in the browser      *      * @param array $args      * @return string       */     public function displayPage($args)  {         $this->CONFIG->set('method', $this->pageOn);         $public_methods = $this->getPublicMethods();         if(in_array($this->pageOn, $public_methods))    {               call_user_func_array(array($this, $this->pageOn), $args);         }         else    {             if(!in_array($this->pageOn, $public_methods))   {                 header("HTTP/1.1 404 Not Found");             }             else {                 $this->CONFIG->set('method', '../missingfunction'); //don't even allow trying the page                 return($this->getErrorPage($this->CONFIG->get('view')."/{$this->pageOn} does not exist."));             }             exit;         }     }      /**      *      * @return string       */     function index() {}      /**      *      * @param string $msg      * @return string       */     protected function getErrorPage($msg = null)    {         $err = '<div class="error errors">%s</div>';         return sprintf($err, $msg);     }      protected function setHelpers(){         $helpers = array();         foreach($this->helpers as $helper){             $help = "{$helper}Helper";             $nameSpacedHelper = "SmallFry\helper\$help";             if(class_exists($nameSpacedHelper) && is_subclass_of($nameSpacedHelper, 'SmallFry\helper\Helper')){                 $this->$helper = new $nameSpacedHelper();                 $helpers[$helper] = $this->$helper;             }         }         $this->template->set('helpers', (object) $helpers);     }      protected function logout(){         session_destroy();         header('Location: '.WEBROOT.'index.php');         exit;     }      /**      *      * @param array $validate      * @param array $values      * @param boolean $exit      * @return boolean       */     protected function validateForm($validate = null, $values = null, $exit = true){          $this->validator = new FormValidator(); //create new validator          if($validate == null){             $validate = $this->validate;         }          foreach($validate as $field => $rules){             foreach($rules as $validate=>$message){                 $this->validator->addValidation($field, $validate, $message);             }         }          return $this->doValidate($values, $exit);     }      protected function doValidate($values = null, $exit = true){         if(!(!isset($_POST) || count($_POST) == 0)){             //some form was submitted             if(!$this->validator->ValidateForm($values)){                 $error = '';                 $error_hash = $this->validator->GetErrors();                 foreach($error_hash as $inpname => $inp_err)                 {                   $error .= $inp_err.PHP_EOL;                 }                 return $this->makeError($error, $exit);                             }         }         return true;     }      protected function makeError($str, $exit = true){         $return = $this->getErrorPage(nl2br($str));         if($exit) exit($return);         return $return;     }      protected function killPage(){ //Throw a 404 for the page         header("HTTP/1.1 404 Not Found");         exit;     } } 5  

Cuando necesito agregar algunas variables a la consulta. Luego, utilizo $ ROW = DB_FETT ($ consulta) para obtener los resultados. Es posible omitir la función DB_FETTE si configuro el 4º parámetro de la función DB en VERDADERO.

¿Cómo puedo hacer mejor las funciones? Quiero decir, ¿está escrito bien o puedo cambiar algo para mejorarlo?

Original en ingles

I have the following functions:

function db ($query, $parameters = false, $results = false, $fetch = false, $error_reporting = true) {      global $db;     global $db_query;      if(!isset($db)) {          $db = new mysqli("localhost", "username", "password", "db");      }      if ($db->connect_error == NULL) {          $db->set_charset("utf8");          if(is_array($parameters)) {              $db_query = $db->prepare($query);              if($db_query) {                  foreach($parameters as $key => $value) {                     $parameters_reference[$key] = &$parameters[$key];                 }                  $ReflectionMethod = new ReflectionMethod ('mysqli_stmt', 'bind_param');                 @$ReflectionMethod -> invokeArgs($db_query, $parameters_reference);                  $execute = $db_query->execute();                  if($execute) {                      if($results === false && $fetch === false) {                          $return = $db_query;                      } else {                          if($results === true) {                             $return = $db_query->get_result();                         }                          if($results === true && $fetch === true) {                             $return = $return->fetch_array(MYSQLI_ASSOC);                         }                     }                  } else {                     $db_error = "Execution error.";                 }              } else {                 $db_error = "Preparation error.";             }          } else {              $return = $db->query($query);              if($parameters === true) {                 $return = $return->fetch_array(MYSQLI_ASSOC);;             }          }      } else {         $db_error = "Connection error.";     }      if(!isset($db_error)) {          return $return;      } else {          if($error_reporting === true) {              die("Database Error: ".$db_error);          } else {              return false;         }     } }  function db_fetch($query) {     return $query->fetch_array(MYSQLI_ASSOC); } 

Their main purpose is to save me time when executing queries to the database. The usage is as follows:

$query = db("SELECT * FROM `table`"); 

When I need to execute a simple query:

$query = db("SELECT * FROM `table` WHERE `var` = ?", ['i', $var], true); 

When I need to add some variables to the query. Then I use $row = db_fetch($query) to get the results. It's possible to skip the db_fetch function if i set 4th parameter of the db function to true.

How can I make the functions better? I mean, is it written well or can I change something to make it better?

     
     
     

Lista de respuestas

1
 
vote
vote
La mejor respuesta
 

Una sugerencia obligatoria: puede mejorar enormemente cualquier código de MySQLI cambiando a PDO. Por lo que su función sería tres veces más corta

  checkArgument(srcPos > size || srcPos < 1, "The srcPos %s is out of bound", srcPos); 3  

Tenga en cuenta que PDO tiene Mucho mejor equivalente de su función DB_Fetch (), le permite obtener el Datos Más sencillos y en más formatos que su combinación de resultados / $ AWKWARD $ / $ FETCH:

  checkArgument(srcPos > size || srcPos < 1, "The srcPos %s is out of bound", srcPos); 4  

Compare estas llamadas explícitas donde siempre puede decir qué devuelve su código con su

  checkArgument(srcPos > size || srcPos < 1, "The srcPos %s is out of bound", srcPos); 5  

Muestra este código a alguien y pregunte qué hay en $ DATA. O mire este código después de un par de meses e intente contarlo a usted mismo sin confundir todos estos parámetros falsos de los verdaderos ANS.

 

An obligatory suggestion: you can greatly improve any mysqli code by switching to PDO. So your function would be three times shorter

function db ($query, $parameters = false) {     global $db;     if(!isset($db))     {         $options = array(             PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,             PDO::ATTR_EMULATE_PREPARES   => FALSE,         );         $dsn = 'mysql:host=localhost;dbname=db;charset=utf8';         $db = new PDO($dsn, "username", "password", $options);     }      if (!$parameters)     {         return $db->query($query);     } else {         $stmt = $db->prepare($query);         $stmt->execute($parameters);         return $stmt;     } } 

note that PDO has much better equivalent of your db_fetch() function, letting you to get the data simpler and in more formats than your awkward $results / $fetch combination:

$row = db("SELECT * FROM t WHERE id=?", [$id])->fetch(); $count = db("SELECT count(*) FROM t")->fetchColumn(); $data = db("SELECT name, id FROM t")->fetchAll(PDO::FETCH_KEY_PAIR); 

compare these explicit calls where you always can tell what does your code return with your

 $data = db("SELECT name, id FROM t", true, true); 

show this code to someone and ask what's in $data. Or look at this code after a couple of months and try to tell it yourself without confusing all these true ans false parameters.

 
 
 
 

Relacionados problema

4  Tirar los datos de la API, permitió la memoria agotada  ( Pulling data from api allowed memory exhausted ) 
Estoy trabajando en un proyecto donde tire los datos (JSON) de una API. Me gustaría manipular estos datos y almacenar esto como información útil en mi DB (MyS...

3  Script de entrada de la base de datos  ( Database input script ) 
¿Es este código seguro y válido? Si es así, ¿puede mejorarse? <?php // conect to the data base $mysqli = new mysqli('localhost','user','p...

19  Una toma en la abstracción de DB  ( A take on db abstraction ) 
Es un poco más de código, pero quería mostrar la clase completa. Resalto los puntos que me gustan después de la fuente. He recortado comentarios ya que no e...

4  Motor de blog o algo  ( Blog engine or somesuch ) 
¿Alguien le diría cómo puedo mejorar esta pieza de código? %d6 ...

7  Modificación de la base de datos de Sakila`  ( Modifying sakila database ) 
Este no es el código de "vida real". Estoy tratando de ampliar la base de datos de muestra 998877766655544330 conocido para MySQL para que sea más complejo....

6  Programa de recuperación de contraseña  ( Password recovery program ) 
Este es un programa de recuperación de contraseña que hice, y solo quiero que se revise. Estos no son todos los archivos para el sistema de inicio de sesión y...

2  PHP Crawler para recoger comentarios sobre los artículos  ( Php crawler to collect comments on articles ) 
Tengo código que analiza las páginas web encuentra comentarios y guarda información sobre comentarios en DB. Tengo una matriz donde se almacenan todas las pág...

9  Primer sistema de inicio de sesión PHP  ( First php login system ) 
¡Este es mi primer intento de un sistema de inicio de sesión! Solo he tenido aproximadamente 2 días de experiencia con MySQL y PHP hasta ahora y esto es lo qu...

4  Mejorar la velocidad del cálculo de RPI  ( Improve speed of rpi calculation ) 
Actualmente toma unos 10 minutos para procesar los equipos de 16K y los juegos de 81k. Pronto podría tener ~ 17K equipos con ~ 160k, y múltiples deportes. Cor...

1  Script de actualización de la base de datos  ( Database update script ) 
Pregunta previa: Script de entrada de base de datos Me gustaría esta nueva pregunta revisada. avdksokiell@myapp.com5 ...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos