ManiaLib 1.0b1 API Reference

Source for file Database.php

Documentation is available at Database.php

  1. <?php
  2. /**
  3.  * MySQL abstraction layer
  4.  * 
  5.  * @see DatabaseConnection
  6.  * @author Maxime Raoust
  7.  * @copyright 2009-2010 NADEO
  8.  * @package ManiaLib
  9.  */
  10.  
  11. /**
  12.  * Database connection
  13.  * 
  14.  * Usage example:
  15.  * <code>
  16.  * <?php
  17.  * require_once(APP_FRAMEWORK_LIBRARIES_PATH.'Database.php');
  18.  * 
  19.  * try
  20.  * {
  21.  *     $database = DatabaseConnection::getInstance();
  22.  *     $result = $database->execute('SELECT * FROM mytable WHERE id < 10');
  23.  *     while($array = $result->fetchAssoc())
  24.  *     {
  25.  *         print_r($array);
  26.  *     }
  27.  *     $myvar = 'Some \'text with quotes\' and "double quotes"';
  28.  *     $myvarQuoted = $database->quote($myvar);
  29.  *     $database->execute( 'INSERT INTO mytable (MyText) VALUES ('.$myvarQuoted.')' );
  30.  *     echo $database->insertID.' is a newly inserted ID';
  31.  * }
  32.  * catch(Exception $e)
  33.  * {
  34.  *     // Error handling...
  35.  * }
  36.  * ?>
  37.  * </code>
  38.  * 
  39.  * @package ManiaLib
  40.  * @subpackage Database
  41.  */
  42. {
  43.     /**
  44.      * @ignore
  45.      */
  46.     static protected $instance;
  47.     /**#@+
  48.      * @ignore
  49.      */
  50.     protected $connection;
  51.     protected $host;
  52.     protected $user;
  53.     protected $password;
  54.     protected $database;
  55.     protected $charset;
  56.     /**#@-*/
  57.     
  58.     /**
  59.      * Get an instance on the database connection object, and connects to the mysql server if needed
  60.      * To configure your connection, override these constants in your config:
  61.      * <ul>
  62.      * <li>APP_DATABASE_HOST</li>
  63.      * <li>APP_DATABASE_USER</li>
  64.      * <li>APP_DATABASE_PASSWORD</li>
  65.      * <li>APP_DATABASE_NAME</li>
  66.      * <li>APP_DATABASE_CHARSET</li>
  67.      * </ul>
  68.      * 
  69.      * @return DatabaseConnection 
  70.      */
  71.     public static function getInstance()
  72.     {
  73.         if (!self::$instance)
  74.         {
  75.             self::$instance new self();
  76.         }
  77.         return self::$instance;
  78.     }
  79.     
  80.     /**
  81.      * @throws DatabaseConnectionException
  82.      * @ignore
  83.      */
  84.     protected function __construct()
  85.     {
  86.         $this->host APP_DATABASE_HOST;
  87.         $this->user APP_DATABASE_USER;
  88.         $this->password APP_DATABASE_PASSWORD;
  89.         
  90.         $this->connection mysql_connect($this->host$this->user$this->password);
  91.                 
  92.         if(!$this->connection)
  93.         {
  94.             throw new DatabaseConnectionException();
  95.         }
  96.  
  97.         $this->select(APP_DATABASE_NAME);    
  98.         $this->setCharset(APP_DATABASE_CHARSET);
  99.     }
  100.     
  101.     /**
  102.      * Sets the charset for the database connection
  103.      */
  104.     function setCharset($charset)
  105.     {
  106.         if($charset != $this->charset)
  107.         {
  108.             $this->charset $charset;
  109.             if(!mysql_set_charset($charset$this->connection))
  110.             {
  111.                 throw new DatabaseException('Couldn\'t set charset: '.$charset);
  112.             }
  113.         }
  114.     }
  115.     
  116.     /**
  117.      * Selects a database
  118.      */
  119.     function select($database)
  120.     {
  121.         if($database != $this->database)
  122.         {
  123.             $this->database $database;
  124.             if(!mysql_select_db($this->database$this->connection))
  125.             {
  126.                 throw new DatabaseSelectionException(mysql_error()mysql_errno());
  127.             }
  128.         }
  129.     }
  130.  
  131.     /**
  132.      * Escape and quote variables so you can insert them safely
  133.      */
  134.     function quote($string)
  135.     {
  136.         return '\''.mysql_real_escape_string($string$this->connection).'\'';
  137.     }
  138.     
  139.     /**
  140.      * Executes a query
  141.      * @param string The query
  142.      * @return DatabaseRecordSet 
  143.      */
  144.     function execute($query)
  145.     {
  146.         $result mysql_query($query$this->connection);
  147.         if(!$result)
  148.         {
  149.             throw new DatabaseQueryException(mysql_error()mysql_errno());
  150.         }
  151.         return new DatabaseRecordSet($result);
  152.     }
  153.     
  154.     /**
  155.      * Get number of affected rows in previous operation
  156.      * @return int 
  157.      */
  158.     function affectedRows()
  159.     {
  160.         return mysql_affected_rows($this->connection);
  161.     }
  162.     
  163.     /**
  164.      * Get the ID generated in the last query
  165.      * @return int 
  166.      */
  167.     function insertID()
  168.     {
  169.         return mysql_insert_id($this->connection);
  170.     }
  171.     
  172.     /**
  173.      * @return bool 
  174.      */
  175.     function isConnected()
  176.     {
  177.         return (!$this->connection)
  178.     }
  179.  
  180.     /**
  181.      * Currently selected database
  182.      * @return string 
  183.      */
  184.     function getDatabase()
  185.     {
  186.         return $this->database;
  187.     }
  188. }
  189.  
  190. /**
  191.  * Database query result
  192.  * @see DatabaseConnection
  193.  * @package ManiaLib
  194.  * @subpackage Database
  195.  */
  196. {
  197.     /**#@+
  198.      * Constants to use with DatabaseRecordSet::fetchArray()
  199.      */
  200.     const FETCH_ASSOC MYSQL_ASSOC;
  201.     const FETCH_NUM MYSQL_NUM;
  202.     const FETCH_BOTH MYSQL_BOTH;
  203.     /**#@-*/
  204.  
  205.     /**
  206.      * MySQL ressource
  207.      * @ignore
  208.      */
  209.     protected $result;
  210.     
  211.     /**
  212.      * @ignore
  213.      */
  214.     function __construct($result)
  215.     {
  216.         $this->result $result;
  217.     }
  218.     
  219.     /**
  220.      * Get a result row as an enumerated array
  221.      * @return array 
  222.      */
  223.     function fetchRow()
  224.     {
  225.         return mysql_fetch_row($this->result);
  226.     }
  227.     
  228.     /**
  229.      * Fetch a result row as an associative array
  230.      * @return array 
  231.      */
  232.     function fetchAssoc()
  233.     {
  234.         return mysql_fetch_assoc($this->result);
  235.     }
  236.     
  237.     /**
  238.      * Fetch a result row as an associative, a numeric array, or both
  239.      * @return array 
  240.      */    
  241.     function fetchArray($resultType self::FETCH_ASSOC)
  242.     {
  243.         return mysql_fetch_array($this->result$resultType);
  244.     }
  245.     
  246.     /**
  247.      * Returns the current row of a result set as an object
  248.      * @param string The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
  249.      * @param array An optional array of parameters to pass to the constructor for class_name objects.
  250.      * @return object 
  251.      */    
  252.     function fetchObject($classNamearray $params array())
  253.     {
  254.         if($className)
  255.         {
  256.             return mysql_fetch_object($this->result$className$params);
  257.         }    
  258.         else
  259.         {
  260.             return mysql_fetch_object($this->result);
  261.         }
  262.     }
  263.     
  264.     /**
  265.      * Gets the number of rows in a result
  266.      * @return int 
  267.      */
  268.     function recordCount()
  269.     {
  270.         return mysql_num_rows($this->result);
  271.     }
  272. }
  273.  
  274. /**
  275.  * Misc database tools
  276.  * @see DatabaseConnection
  277.  * @package ManiaLib
  278.  * @subpackage Database
  279.  */
  280. abstract class DatabaseTools
  281. {
  282.     /**
  283.      * Returns the "LIMIT x,x" string depending on both values
  284.      */
  285.     static function getLimitString($offset$length)
  286.     {
  287.         if(!$offset && !$length)
  288.         {
  289.             return '';
  290.         }
  291.         elseif(!$offset && $length==1)
  292.         {
  293.             return 'LIMIT 1';
  294.         }
  295.         else
  296.         {
  297.             return 'LIMIT '.$offset.', '.$length;
  298.         }
  299.     }
  300.     
  301.     /**
  302.      * Returns string like "(name1, name2) VALUES (value1, value2)"
  303.      */
  304.     static function getValuesString(array $values)
  305.     {
  306.         return 
  307.             '('.implode(', 'array_keys($values)).') '.
  308.             'VALUES '.
  309.             '('.implode(', '$values).')';
  310.     }
  311.     
  312.     /**
  313.      * Returns string like "name1=VALUES(name1), name2=VALUES(name2)"
  314.      */
  315.     static function getOnDuplicateKeyUpdateValuesString(array $valueNames)
  316.     {
  317.         $strings array()
  318.         foreach($valueNames as $valueName)
  319.         {
  320.             $strings[$valueName.'=VALUES('.$valueName.')';
  321.         }
  322.         return implode(', '$strings);
  323.     }
  324. }
  325.  
  326. /**
  327.  * @package ManiaLib
  328.  * @subpackage Database
  329.  * @ignore
  330.  */
  331. class DatabaseException extends Exception {}
  332.  
  333. /**
  334.  * @package ManiaLib
  335.  * @subpackage Database
  336.  * @ignore
  337.  */
  338. class DatabaseConnectionException extends DatabaseException {}
  339.  
  340. /**
  341.  * @package ManiaLib
  342.  * @subpackage Database
  343.  * @ignore
  344.  */
  345. class DatabaseSelectionException extends DatabaseException {}
  346.  
  347. /**
  348.  * @package ManiaLib
  349.  * @subpackage Database
  350.  * @ignore
  351.  */
  352. class DatabaseQueryException extends DatabaseException {}
  353.  
  354. ?>