Code Snippets

  

PHP Source Code


Welcome to Dream.In.Code
Getting PHP Help is Easy!

Join 99,782 PHP Programmers for FREE! Ask your question and get quick answers from experts. There are 1,526 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!




MYSQL Abstraction Layer

Use this Abstraction layer to keep your business logic seperate. Change Options Below for either mysql or mysqli drivers. query() can return resource, associative array, or object depending on args and config. When error occurs, db::error() is called, change this to log errors or perform whatever you like, or change config 'display_errors' to be silent. Take a moment and look through the config to get a better understanding. I will release an API and user guide later to help you get started. Query() can return Resource, Associative Array, or Object Free to use and modify to your liking, just keep this comment block here. Make sure you run your vars through prepare() before using them in query() to protect against SQL Injection.

Submitted By: joeyadms
Actions:
Rating:
Views: 224

Language: PHP

Last Modified: May 22, 2008
Instructions: SEE http://www.bin.joeyadams.net/mysql_ab_pro/ FOR DETAILS ON USAGE!

/**
* MYSQL Abstraction Pro
*
* Including iObject, an improved result object.
*/



To get a DB instance, use db::getInstance();
$DB = db::getInstance();

/**
* Cleaning Variables
*/

To clean Variables, pass them to db::prepare($var) , it will return cleaned
string or array.

//String
$var = $_POST['var'];
$clean_var = $DB->prepare($var);

//Array
$array = array('a','b','c');
$clean_arr = $DB->prepare($array);


/**
* Querying
*
* Set Default Query Return options in config
*/

// Query with default settings
$q = "SELECT * FROM users";
$DB->query($q);

//Query returning Resource
$DB->query($q,"RES");
-or-
$DB->query($q,"RESOURCE");

// Query returning Associative Array
$rows = $DB->query($q,"ASSOS")
-or-
$rows = $DB->query($q,"ASSOCIATIVE");

// Num Rows and Affected Rows
echo $rows['num_rows'];
echo $rows['affected_rows'];

foreach($rows as $row){
echo $row['username'];
}

// Query Returning all Object
$result = $DB->query($q,"OBJ");
-or-
$result = $DB->query($q,"OBJECT");

// Num Rows and Affected Rows
echo $result->num_rows;
echo $result->affected_rows;

foreach($result->rows as $row){
echo $row->username;
// Escaping built in
echo $row->escape('username');
}


/**
* EXTENDING!
*
* You can extend this, or modify it in any way you want, just leave my top
* comment block in place.
*
*
* iObject Extending::::
* The new return improved Object can be extended to provide more power to your results.
*
* class qresult, is the base result class returned. It has properties for num_rows and affected_rows. It stores an array $rows containing instances
* of qrow for each row returned.
*
* QResult also has a search function, fetchRow($var,$val,$return_style), That will search through the returned rows and return an qrow instance of the first
* matching row. If the last parameter , $return_style , is set, it will return an array of instances of all rows that match.
*
* Extend QResult to give functionality to the result object returned from a query.
*
*
* Qrow stores dynamic properties based on the vars and vals returned by the database. The real power of iObject comes in Qrow. By extending
* Qrow, you will be able to easily manipulate returned results with little effort.
*
* By Default, Qrow comes with one method, escape($var) , this will return a htmlspecialchar() escaped value from one of the properties specified with
* $var. For example, to escape and echo the username of a row, you would "echo $row->escape('username');"
*/

Snippet


  1. <?php
  2. /**
  3. * @name MYSQL Database Abstraction Layer
  4. * @author Joey Adams
  5. * @see http://bin.joeyadams.net/mysql_ab_pro/
  6. * @version 4.0
  7. * @uses
  8. * Use this Abstraction layer to keep your business logic seperate.
  9. *
  10. * Change Options Below for either mysql or mysqli drivers.
  11. *
  12. * By Default query() returns Associative array, change options to return resource, or object.
  13. *
  14. * Note: On error, function db::error($str) is called, which just die()'s with error string.
  15. * Modify this to log errors, or turn off for silence, or whatever you like. Change Error in
  16. * config for silence.
  17. *
  18. * Free to use and modify to your liking, just keep this comment block here.
  19. *
  20. * Make sure you run your vars through prepare() before using them in query() to protect
  21. * against SQL Injection.
  22. *
  23. *
  24. * When performing query() , it accepts 2 arguments. query($string,$return_type);
  25. * String is the query string. Return type is one of the below;
  26. * ASSOS = Associative Array
  27. * OBJ = Return Object
  28. * RES = return resource
  29. *
  30. * If no type is given, it will return type per config.
  31. *
  32. *
  33. * @copyright GPL (http://www.gnu.org/licenses/gpl.txt)
  34. *   This program is free software: you can redistribute it and/or modify
  35. *   it under the terms of the GNU General Public License as published by
  36. *   the Free Software Foundation, either version 3 of the License, or
  37. *   (at your option) any later version.
  38. *
  39. *   This program is distributed in the hope that it will be useful,
  40. *   but WITHOUT ANY WARRANTY; without even the implied warranty of
  41. *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  42. *   GNU General Public License for more details.
  43. *
  44. *   You should have received a copy of the GNU General Public License
  45. *   along with this program.  If not, see <http://www.gnu.org/licenses/>
  46. *
  47. */
  48.  
  49.  
  50. class DB {
  51.        
  52.         // Options
  53.         /**
  54.         * Set MYSQL Driver
  55.         * 0 = MYSQL
  56.         * 1 = MYSQLI
  57.         *
  58.         * @var int driver
  59.         */
  60.         private $driver = 1;
  61.         /**
  62.         * Default Query Results Return Style
  63.         *
  64.         * 0 = Return Resource
  65.         * 1 = Return Associative Array
  66.         * 2 = Return Object
  67.         *
  68.         * @var int def_return_style
  69.         */
  70.         private $def_return_style = 1;
  71.        
  72.         /**
  73.         * Log File to store Error info
  74.         * Make sure this file is readable/writeable
  75.         *
  76.         * @var str log_file
  77.         */
  78.         private $log_file = "mysql_pro_error.log";
  79.        
  80.         /**
  81.         * Log Erros
  82.         * 0 = Do not log errors
  83.         * 1 = Log Errors
  84.         *
  85.         * Logs errors to log_file above
  86.         *
  87.         */
  88.         private $log_errors = 0;
  89.        
  90.         /**
  91.         * Set whether to die() with error string
  92.         *
  93.         * 0 = Do not display, silent mode.
  94.         * 1 = die() with errors.
  95.         *
  96.         * Note: Change db::error() to change how
  97.         * errors are handled
  98.         *
  99.         * @var unknown_type
  100.         */
  101.         private $display_errors = 0;
  102.                
  103.         //-- End Options --
  104.        
  105.        
  106.         // Connection Info
  107.         /**
  108.         * MYSQL Server Host
  109.         * @var str host
  110.         */
  111.         private $host = "host";
  112.         /**
  113.         * MYSQL Username
  114.         * @var str username
  115.         */
  116.         private $username = "username";
  117.         /**
  118.         * MYSQL Password
  119.         * @var str password
  120.         */
  121.         private $password = "password";
  122.         /**
  123.         * MYSQL Default Database
  124.         * Set this to default db to use, although you can
  125.         * pass a db name to getInstance() to use different one
  126.         *
  127.         * @var str def_db
  128.         */
  129.         private $def_db = "test";
  130.         //-- End Connection Info --
  131.        
  132.        
  133.         /**
  134.         *
  135.         *
  136.         * Edit Below This line at your own risk
  137.         *
  138.         *
  139.         */
  140.        
  141.         /**
  142.         * Variable holds plugin for iObject
  143.         *
  144.         * @var str class_name
  145.         */
  146.         private $iobj;
  147.        
  148.         /**
  149.         * Variables holds plugin for iRow
  150.         *
  151.         * @var unknown_type
  152.         */
  153.         private $irowobj;
  154.        
  155.        
  156.         /**
  157.         * MYSQL Connection Link
  158.         * Holds Link for connection for functionality
  159.         *
  160.         * @var static MYSQL_CONNECTION
  161.         */
  162.         private static $_link;
  163.        
  164.         /**
  165.         * Array that stores connections
  166.         * made with create()
  167.         *
  168.         * @var array
  169.         */
  170.         private $_link_array = array();
  171.        
  172.         /**
  173.         * Establish MYSQL Connection
  174.         * with either mysql, or mysqli driver
  175.         * based on config.
  176.         *
  177.         * Accepts 1 param for database name,
  178.         * If null, uses self::def_db
  179.         *
  180.         * @param str $db
  181.         */
  182.         public function __construct($db = null){
  183.                 if(!is_null($db)){
  184.                         $this->def_db = $db;
  185.                 }
  186.                 if($this->driver){
  187.                         $this->_link = new mysqli($this->host,$this->username,$this->password,$this->def_db);
  188.                         if(mysqli_connect_errno()){
  189.                                 $this->error(mysqli_connect_error());
  190.                         }
  191.                 } else {
  192.                         $this->_link = mysql_connect($this->host,$this->username,$this->password);
  193.                         mysql_select_db($this->def_db,$this->_link);
  194.                         if(mysql_errno()){
  195.                                 $this->error(mysql_error());
  196.                         }
  197.                 }
  198.                 $this->_link_array['def'] = $this->_link;
  199.         }
  200.        
  201.         /**
  202.         * Closes MYSQL Connection
  203.         *
  204.         */
  205.         public function __destruct(){
  206.                 if($this->driver){
  207.                         $this->_link->close();
  208.                 } else {
  209.                         mysql_close($this->_link);
  210.                 }
  211.         }
  212.        
  213.         /**
  214.         * Add extended class plugin. Extends iObject return style.
  215.         *
  216.         * @param string $class_name
  217.         */
  218.         public function iobjectPlugin($class_name){
  219.                 if(class_exists($class_name) && array_key_exists('iobject',class_parents($class_name))){
  220.                         $this->iobj = $class_name;
  221.                 }
  222.         }
  223.        
  224.         /**
  225.         * Add extended class plugin. Extends iRow for iObject return style.
  226.         *
  227.         * @param string $class_name
  228.         */
  229.         public function irowPlugin($class_name){
  230.                 if(class_exists($class_name) && array_key_exists('irow',class_parents($class_name))){
  231.                         $this->irowobj = $class_name;
  232.                 }
  233.         }
  234.        
  235.         /**
  236.         * Called when error occurs
  237.         *
  238.         * @param str $error
  239.         */
  240.         public function error($error){
  241.                 if($this->log_errors){
  242.                         if(!$fp = fopen($this->log_file,'a')){
  243.                                 if($this->display_errors){
  244.                                         die("Error Handler: Could not open file for writing, ".$this->log_file);
  245.                                 }
  246.                         }
  247.                         $date = date(DATE_RFC822);
  248.                         $err = $date . " - " . $error . "\n";
  249.                         if(!fwrite($fp,$err)){
  250.                                 if($this->display_errors){
  251.                                         die("Error Handler:Could Not Write To File");
  252.                                 }
  253.                         }
  254.                         fclose($fp);
  255.                 }
  256.                 if($this->display_errors){
  257.                         die($error);
  258.                 }
  259.         }
  260.        
  261.         /**
  262.         * Returns instance of MYSQL
  263.         *
  264.         * Use this to init DB(), or to
  265.         * get an instance of the connection.
  266.         *
  267.         * Makes sure only 1 persistent connection
  268.         * is maintained.
  269.         *
  270.         * Pass a string when initializing if you want
  271.         * to use a different database than in config.
  272.         *
  273.         * @param str $db
  274.         * @return MYSQL_CONNECTION
  275.         */
  276.         public function getInstance($db = null){
  277.                 if(is_null(self::$_link)){
  278.                         self::$_link = new DB($db);
  279.                 }
  280.                 return self::$_link;
  281.         }
  282.        
  283.         /**
  284.         * Wrapper for Real_Escape_String
  285.         *
  286.         * Accepts either array, or string
  287.         * and returns escaped vars.
  288.         *
  289.         * Use this before query() on vars to
  290.         * protect from sql injection
  291.         *
  292.         * @param str,array $var
  293.         * @return str,array $clean
  294.         */
  295.         public function prepare($var){
  296.                 if(is_array($var)){
  297.                         if($this->driver){
  298.                                 foreach($var as $key=>$val){
  299.                                         $clean[$key] = $this->_link->real_escape_string($val);
  300.                                 }
  301.                         } else {
  302.                                 foreach($var as $key=>$val){
  303.                                         $clean[$key] = mysql_real_escape_string($val,$this->_link);
  304.                                 }
  305.                         }
  306.                 } else {
  307.                         if($this->driver){
  308.                                 $clean = $this->_link->real_escape_string($var);
  309.                         } else {
  310.                                 $clean = mysql_real_escape_string($var,$this->_link);
  311.                         }
  312.                 }
  313.                 return $clean;
  314.         }
  315.        
  316.         /**
  317.         * Performs Query Against Database
  318.         *
  319.         * Accepts two args, the query string,
  320.         * and an optional return style.
  321.         *
  322.         * Return Style Can be
  323.         * 'OBJ' or 'OBJECT' = Return Object
  324.         * 'RES' or 'RESOURCE' = Return Resource
  325.         * 'ASSOC' or 'ASSOCIATIVE' = Return Associative Array
  326.         *
  327.         * Note:: If return_style is omitted, return will be determined
  328.         * by config above.
  329.         *
  330.         * @param str $query
  331.         * @return MYSQL_RESULT,ASSOC_ARRAY
  332.         */
  333.         public function query($query,$return_style = null){
  334.                 $return_style = $this->_getReturnStyle($return_style);
  335.                 if($this->driver){
  336.                         if(!$resultSet = $this->_link->query($query)){
  337.                                 $this->error(mysqli_error($this->_link));
  338.                         }
  339.                         if($return_style){
  340.                                 if($return_style == 1){
  341.                                         $returnResult['affected_rows'] = $this->_link->affected_rows;
  342.                                         if(is_object($resultSet)){
  343.                                         $returnResult['num_rows'] = $resultSet->num_rows;
  344.                                                 if($resultSet->num_rows){
  345.                                                         $i=0;
  346.                                                         while($result = $resultSet->fetch_assoc()){
  347.                                                                 foreach($result as $key=>$val){
  348.                                                                         $returnResult[$i][$key] = $val;
  349.                                                                 }
  350.                                                                 $i++;
  351.                                                         }
  352.                                                 }
  353.                                         }       
  354.                                 } elseif ($return_style == 2){
  355.                                         if(!is_null($this->iobj)){
  356.                                                 $i_obj = $this->iobj;
  357.                                         } else {
  358.                                                 $i_obj = "iobject";
  359.                                         }
  360.                                         $iobject = new $i_obj($this->irowobj);
  361.                                         $iobject->query = $query;
  362.                                         $iobject->affected_rows = $this->_link->affected_rows;
  363.                                         if(is_object($resultSet)){
  364.                                                 $iobject->num_rows = $resultSet->num_rows;
  365.                                                 if($resultSet->num_rows){
  366.                                                         while($result = $resultSet->fetch_assoc()){
  367.                                                                 $row = $iobject->newRow();
  368.                                                                 foreach($result as $key=>$val){
  369.                                                                         $row->$key = $val;
  370.                                                                 }               
  371.                                                         }
  372.                                                 }
  373.                                         }
  374.                                         $returnResult = &$iobject;
  375.                                 }
  376.                         } else {
  377.                                 $returnResult = $resultSet;
  378.                         }
  379.                 } else {
  380.                         if(!$resultSet = mysql_query($query,$this->_link)){
  381.                                 $this->error(mysql_error());
  382.                         }
  383.                         if($return_style){
  384.                                 if($return_style == 1){
  385.                                         $returnResult['affected_rows'] = mysql_affected_rows();
  386.                                         if(is_resource($resultSet)){
  387.                                         $returnResult['num_rows'] = mysql_num_rows($resultSet);
  388.                                                 if($returnResult['num_rows']){       
  389.                                                         $i=0;
  390.                                                         while($result = mysql_fetch_assoc($resultSet)){
  391.                                                                 foreach($result as $key=>$val){
  392.                                                                         $returnResult[$i][$key] = $val;
  393.                                                                 }
  394.                                                                 $i++;
  395.                                                         }
  396.                                                 }
  397.                                         }       
  398.                                 } elseif ($return_style == 2){
  399.                                         if