Jump to content
MakeWebGames

MySQLi Easy class


Recommended Posts

Hey guys,

For my new project I've decided to work with MySQLi as it has many strengths over MySQL. Since I'm quite lazy and didnt want to write 5+ lines for a query, I decided to create a simple class so I could write 1 line, and it run the query, bind the params, and such MySQLi goodies. I ended up using some code from the php manuals comments. So by using the class below, I can easily call a query by doing something like

$users = $db->__query('SELECT * FROM `users` WHERE (`userid` = ?);', array('i', $userid));

This will then return the results as an array, for instance $user['userid'']....This could easily be changed to make it into objects such as $user->userid, Thats the way I make it at first, but then changed to array.

Just to let you know, I have this in a db folder, and the config file in a seperate folder called config, both being in the home dir. The config file is this;

 

<?php
/* @author Daniel Hanson <[email protected]>
*
* First off, Lets define some variables
*/
define('host', 'localhost');
define('name', 'root');
define('pass', '');
define('db', 'databse');
/*
* Thats all for now, this file is complete.
*/

 

And for the db file.

 

<?php
/* @author Daniel Hanson <[email protected]>
* @copyright Copyright (c) 2012, Daniel Hanson
* This was built by Daniel Hanson, and released for free on makewebgames.io
* Do not remove this, It affects nothing in the script.
*
* First off, see if we have passed the defines we need
*/

if(!defined('host')) {
   include_once(dirname(dirname(__FILE__)) .'/config/db.config.php'); //Get the database config we need.
}

//Just extend the mysqli class from PHP
class database extends mysqli {
   //Start the class
   public function __construct($host, $user, $pass, $db) {
       parent::__construct($host, $user, $pass, $db);
       if (mysqli_connect_error()) {
           die('Database Error: ('. mysqli_connect_errno() .') '. mysqli_connect_error());
       }
   }
   //End the class when its all over
   function __destruct() {
       parent::close();
   }

   function __query($sql, $arrParams) {
       $result = array(); 
       //$result = new stdClass(); 
       if ($stmt = $this->prepare($sql)) {
           if(count($arrParams) == 0) {
           } else {
           $arrParams = $this->getRefArray($arrParams);
           $method = new ReflectionMethod('mysqli_stmt', 'bind_param'); 
           $method->invokeArgs($stmt, $arrParams);
           }
           $stmt->execute() or die($this->error);
           $meta = $stmt->result_metadata(); 
           if (!$meta) {
               //$result->affected_rows = $stmt->affected_rows;
               //$result->insert_id = $stmt->insert_id;
               $result['affected_rows'] = $stmt->affected_rows; 
               $result['insert_id'] = $stmt->insert_id;
               $stmt->close();
               return $result;
           } else { 
               $stmt->store_result(); 
               $params = array(); 
               $row = array(); 
                   while ($field = $meta->fetch_field()) {
                       $params[] = &$row[$field->name]; 
                   }
               $meta->close(); 
               $method = new ReflectionMethod('mysqli_stmt', 'bind_result'); 
               $method->invokeArgs($stmt, $params);            
               $result = array(); 
               while ($stmt->fetch()) {
                   $obj = array();
                   //$obj = new stdClass(); 
                   foreach($row as $key => $val) { 
                       $obj[$key] = $val;
                       //$obj->$key = $val
                   }
                   $result[] = $obj;
               } 
               $stmt->free_result(); 
           } 
           $stmt->close(); 
       } else {
            printf("Prepared Statement Error: %s\n", $this->error);
       }
       return @$result[0]; 
   } 

   private function getRefArray($a) { 
   if (strnatcmp(phpversion(),'5.3')>=0) { 
       $ret = array(); 
       foreach($a as $key => $val) { 
           $ret[$key] = &$a[$key]; 
       } 
       return $ret; 
   } 
   return $a;
   }
}



/*
* Create the db for all to use.
*/

$db = new database(host, name, pass, db);
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...