dbo_mysqli.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: dbo__mysqli_8php-source.html 580 2008-07-01 14:45:49Z gwoo $ */
00003 /**
00004  * MySQLi layer for DBO
00005  *
00006  * Long description for file
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
00011  * Copyright 2005-2008, Cake Software Foundation, Inc.
00012  *                              1785 E. Sahara Avenue, Suite 490-204
00013  *                              Las Vegas, Nevada 89104
00014  *
00015  * Licensed under The MIT License
00016  * Redistributions of files must retain the above copyright notice.
00017  *
00018  * @filesource
00019  * @copyright       Copyright 2005-2008, Cake Software Foundation, Inc.
00020  * @link                http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00021  * @package         cake
00022  * @subpackage      cake.cake.libs.model.datasources.dbo
00023  * @since           CakePHP(tm) v 1.1.4.2974
00024  * @version         $Revision: 580 $
00025  * @modifiedby      $LastChangedBy: gwoo $
00026  * @lastmodified    $Date: 2008-07-01 09:45:49 -0500 (Tue, 01 Jul 2008) $
00027  * @license         http://www.opensource.org/licenses/mit-license.php The MIT License
00028  */
00029 
00030 /**
00031  * Short description for class.
00032  *
00033  * Long description for class
00034  *
00035  * @package     cake
00036  * @subpackage  cake.cake.libs.model.datasources.dbo
00037  */
00038 class DboMysqli extends DboSource {
00039 /**
00040  * Enter description here...
00041  *
00042  * @var unknown_type
00043  */
00044     var $description = "Mysqli DBO Driver";
00045 /**
00046  * Enter description here...
00047  *
00048  * @var unknown_type
00049  */
00050     var $startQuote = "`";
00051 /**
00052  * Enter description here...
00053  *
00054  * @var unknown_type
00055  */
00056     var $endQuote = "`";
00057 /**
00058  * index definition, standard cake, primary, index, unique
00059  *
00060  * @var array
00061  */
00062     var $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
00063 
00064 /**
00065  * Base configuration settings for Mysqli driver
00066  *
00067  * @var array
00068  */
00069     var $_baseConfig = array(
00070         'persistent' => true,
00071         'host' => 'localhost',
00072         'login' => 'root',
00073         'password' => '',
00074         'database' => 'cake',
00075         'port' => '3306',
00076         'connect' => 'mysqli_connect'
00077     );
00078 /**
00079  * Mysqli column definition
00080  *
00081  * @var array
00082  */
00083     var $columns = array(
00084         'primary_key' => array('name' => 'DEFAULT NULL auto_increment'),
00085         'string' => array('name' => 'varchar', 'limit' => '255'),
00086         'text' => array('name' => 'text'),
00087         'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
00088         'float' => array('name' => 'float', 'formatter' => 'floatval'),
00089         'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00090         'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00091         'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
00092         'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
00093         'binary' => array('name' => 'blob'),
00094         'boolean' => array('name' => 'tinyint', 'limit' => '1')
00095     );
00096 /**
00097  * Connects to the database using options in the given configuration array.
00098  *
00099  * @return boolean True if the database could be connected, else false
00100  */
00101     function connect() {
00102         $config = $this->config;
00103         $this->connected = false;
00104         
00105         if (is_numeric($config['port'])) {
00106             $config['socket'] = null;
00107         } else {
00108             $config['socket'] = $config['port'];
00109             $config['port'] = null;
00110         }
00111         
00112         $this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], $config['database'], $config['port'], $config['socket']);
00113 
00114         if ($this->connection !== false) {
00115             $this->connected = true;
00116         }
00117 
00118         if (!empty($config['encoding'])) {
00119             $this->setEncoding($config['encoding']);
00120         }
00121         return $this->connected;
00122     }
00123 /**
00124  * Disconnects from database.
00125  *
00126  * @return boolean True if the database could be disconnected, else false
00127  */
00128     function disconnect() {
00129         @mysqli_free_result($this->results);
00130         $this->connected = !@mysqli_close($this->connection);
00131         return !$this->connected;
00132     }
00133 /**
00134  * Executes given SQL statement.
00135  *
00136  * @param string $sql SQL statement
00137  * @return resource Result resource identifier
00138  * @access protected
00139  */
00140     function _execute($sql) {
00141         if (preg_match('/^\s*call/i', $sql)) {
00142             return $this->_executeProcedure($sql);
00143         } else {
00144             return mysqli_query($this->connection, $sql);
00145         }
00146     }
00147 /**
00148  * Executes given SQL statement (procedure call).
00149  *
00150  * @param string $sql SQL statement (procedure call)
00151  * @return resource Result resource identifier for first recordset
00152  * @access protected
00153  */
00154     function _executeProcedure($sql) {
00155         $answer = mysqli_multi_query($this->connection, $sql);
00156 
00157         $firstResult = mysqli_store_result($this->connection);
00158 
00159         if (mysqli_more_results($this->connection)) {
00160             while($lastResult = mysqli_next_result($this->connection));
00161         }
00162         return $firstResult;
00163     }
00164 /**
00165  * Returns an array of sources (tables) in the database.
00166  *
00167  * @return array Array of tablenames in the database
00168  */
00169     function listSources() {
00170         $cache = parent::listSources();
00171         if ($cache != null) {
00172             return $cache;
00173         }
00174         $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
00175 
00176         if (!$result) {
00177             return array();
00178         } else {
00179             $tables = array();
00180 
00181             while ($line = mysqli_fetch_array($result)) {
00182                 $tables[] = $line[0];
00183             }
00184             parent::listSources($tables);
00185             return $tables;
00186         }
00187     }
00188 /**
00189  * Returns an array of the fields in given table name.
00190  *
00191  * @param string $tableName Name of database table to inspect
00192  * @return array Fields in table. Keys are name and type
00193  */
00194     function describe(&$model) {
00195 
00196         $cache = parent::describe($model);
00197         if ($cache != null) {
00198             return $cache;
00199         }
00200 
00201         $fields = false;
00202         $cols = $this->query('DESCRIBE ' . $this->fullTableName($model));
00203 
00204         foreach ($cols as $column) {
00205             $colKey = array_keys($column);
00206             if (isset($column[$colKey[0]]) && !isset($column[0])) {
00207                 $column[0] = $column[$colKey[0]];
00208             }
00209             if (isset($column[0])) {
00210                 $fields[$column[0]['Field']] = array(
00211                     'type'      => $this->column($column[0]['Type']),
00212                     'null'      => ($column[0]['Null'] == 'YES' ? true : false),
00213                     'default'   => $column[0]['Default'],
00214                     'length'    => $this->length($column[0]['Type'])
00215                 );
00216                 if(!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
00217                     $fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
00218                 }
00219             }
00220         }
00221 
00222         $this->__cacheDescription($this->fullTableName($model, false), $fields);
00223         return $fields;
00224     }
00225 /**
00226  * Returns a quoted and escaped string of $data for use in an SQL statement.
00227  *
00228  * @param string $data String to be prepared for use in an SQL statement
00229  * @param string $column The column into which this data will be inserted
00230  * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
00231  * @return string Quoted and escaped data
00232  */
00233     function value($data, $column = null, $safe = false) {
00234         $parent = parent::value($data, $column, $safe);
00235 
00236         if ($parent != null) {
00237             return $parent;
00238         }
00239 
00240         if ($data === null) {
00241             return 'NULL';
00242         }
00243 
00244         if ($data === '') {
00245             return  "''";
00246         }
00247 
00248         switch ($column) {
00249             case 'boolean':
00250                 $data = $this->boolean((bool)$data);
00251             break;
00252             case 'integer' :
00253             case 'float' :
00254             case null :
00255                 if (is_numeric($data) && strpos($data, ',') === false && $data[0] != '0' && strpos($data, 'e') === false) {
00256                     break;
00257                 }
00258             default:
00259                 $data = "'" . mysqli_real_escape_string($this->connection, $data) . "'";
00260             break;
00261         }
00262 
00263         return $data;
00264     }
00265 /**
00266  * Begin a transaction
00267  *
00268  * @param unknown_type $model
00269  * @return boolean True on success, false on fail
00270  * (i.e. if the database/model does not support transactions).
00271  */
00272     function begin(&$model) {
00273         if (parent::begin($model) && $this->execute('START TRANSACTION')) {
00274             $this->_transactionStarted = true;
00275             return true;
00276         }
00277         return false;
00278     }
00279 /**
00280  * Returns a formatted error message from previous database operation.
00281  *
00282  * @return string Error message with error number
00283  */
00284     function lastError() {
00285         if (mysqli_errno($this->connection)) {
00286             return mysqli_errno($this->connection).': '.mysqli_error($this->connection);
00287         }
00288         return null;
00289     }
00290 /**
00291  * Returns number of affected rows in previous database operation. If no previous operation exists,
00292  * this returns false.
00293  *
00294  * @return integer Number of affected rows
00295  */
00296     function lastAffected() {
00297         if ($this->_result) {
00298             return mysqli_affected_rows($this->connection);
00299         }
00300         return null;
00301     }
00302 /**
00303  * Returns number of rows in previous resultset. If no previous resultset exists,
00304  * this returns false.
00305  *
00306  * @return integer Number of rows in resultset
00307  */
00308     function lastNumRows() {
00309         if ($this->hasResult()) {
00310             return @mysqli_num_rows($this->_result);
00311         }
00312         return null;
00313     }
00314 /**
00315  * Returns the ID generated from the previous INSERT operation.
00316  *
00317  * @param unknown_type $source
00318  * @return in
00319  */
00320     function lastInsertId($source = null) {
00321         $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
00322         if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
00323             return $id[0]['insertID'];
00324         }
00325 
00326         return null;
00327     }
00328 /**
00329  * Converts database-layer column types to basic types
00330  *
00331  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00332  * @return string Abstract column type (i.e. "string")
00333  */
00334     function column($real) {
00335         if (is_array($real)) {
00336             $col = $real['name'];
00337             if (isset($real['limit'])) {
00338                 $col .= '('.$real['limit'].')';
00339             }
00340             return $col;
00341         }
00342 
00343         $col = str_replace(')', '', $real);
00344         $limit = $this->length($real);
00345         if (strpos($col, '(') !== false) {
00346             list($col, $vals) = explode('(', $col);
00347         }
00348 
00349         if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
00350             return $col;
00351         }
00352         if ($col == 'tinyint' && $limit == 1) {
00353             return 'boolean';
00354         }
00355         if (strpos($col, 'int') !== false) {
00356             return 'integer';
00357         }
00358         if (strpos($col, 'char') !== false || $col == 'tinytext') {
00359             return 'string';
00360         }
00361         if (strpos($col, 'text') !== false) {
00362             return 'text';
00363         }
00364         if (strpos($col, 'blob') !== false) {
00365             return 'binary';
00366         }
00367         if (in_array($col, array('float', 'double', 'decimal'))) {
00368             return 'float';
00369         }
00370         if (strpos($col, 'enum') !== false) {
00371             return "enum($vals)";
00372         }
00373         if ($col == 'boolean') {
00374             return $col;
00375         }
00376         return 'text';
00377     }
00378 /**
00379  * Gets the length of a database-native column description, or null if no length
00380  *
00381  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00382  * @return integer An integer representing the length of the column
00383  */
00384     function length($real) {
00385         $col = str_replace(array(')', 'unsigned'), '', $real);
00386         $limit = null;
00387 
00388         if (strpos($col, '(') !== false) {
00389             list($col, $limit) = explode('(', $col);
00390         }
00391 
00392         if ($limit != null) {
00393             return intval($limit);
00394         }
00395         return null;
00396     }
00397 /**
00398  * Enter description here...
00399  *
00400  * @param unknown_type $results
00401  */
00402     function resultSet(&$results) {
00403         $this->results =& $results;
00404         $this->map = array();
00405         $num_fields = mysqli_num_fields($results);
00406         $index = 0;
00407         $j = 0;
00408         while ($j < $num_fields) {
00409             $column = mysqli_fetch_field_direct($results, $j);
00410             if (!empty($column->table)) {
00411                 $this->map[$index++] = array($column->table, $column->name);
00412             } else {
00413                 $this->map[$index++] = array(0, $column->name);
00414             }
00415             $j++;
00416         }
00417     }
00418 /**
00419  * Fetches the next row from the current result set
00420  *
00421  * @return unknown
00422  */
00423     function fetchResult() {
00424         if ($row = mysqli_fetch_row($this->results)) {
00425             $resultRow = array();
00426             $i = 0;
00427             foreach ($row as $index => $field) {
00428                 $table = $column = null;
00429                 if (count($this->map[$index]) == 2) {
00430                     list($table, $column) = $this->map[$index];
00431                 }
00432                 $resultRow[$table][$column] = $row[$index];
00433                 $i++;
00434             }
00435             return $resultRow;
00436         } else {
00437             return false;
00438         }
00439     }
00440 /**
00441  * Sets the database encoding
00442  *
00443  * @param string $enc Database encoding
00444  */
00445     function setEncoding($enc) {
00446         return $this->_execute('SET NAMES ' . $enc) != false;
00447     }
00448 /**
00449  * Gets the database encoding
00450  *
00451  * @return string The database encoding
00452  */
00453     function getEncoding() {
00454         return mysqli_client_encoding($this->connection);
00455     }
00456 /**
00457  * Checks if the result is valid
00458  *
00459  * @return boolean True if the result is valid, else false
00460  */
00461     function hasResult() {
00462         return is_object($this->_result);
00463     }   
00464 }
00465 ?>