dbo_mysqli.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: dbo__mysqli_8php-source.html 675 2008-12-26 00:27:14Z 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.dbo
00023  * @since           CakePHP(tm) v 1.1.4.2974
00024  * @version         $Revision: 675 $
00025  * @modifiedby      $LastChangedBy: gwoo $
00026  * @lastmodified    $Date: 2008-12-25 16:27:14 -0800 (Thu, 25 Dec 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.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  * Base configuration settings for Mysqli driver
00059  *
00060  * @var array
00061  */
00062     var $_baseConfig = array('persistent' => true,
00063                                 'host' => 'localhost',
00064                                 'login' => 'root',
00065                                 'password' => '',
00066                                 'database' => 'cake',
00067                                 'port' => '3306',
00068                                 'connect' => 'mysqli_connect');
00069 /**
00070  * Mysqli column definition
00071  *
00072  * @var array
00073  */
00074     var $columns = array('primary_key' => array('name' => 'int(11) DEFAULT NULL auto_increment'),
00075                         'string' => array('name' => 'varchar', 'limit' => '255'),
00076                         'text' => array('name' => 'text'),
00077                         'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
00078                         'float' => array('name' => 'float', 'formatter' => 'floatval'),
00079                         'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00080                         'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00081                         'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
00082                         'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
00083                         'binary' => array('name' => 'blob'),
00084                         'boolean' => array('name' => 'tinyint', 'limit' => '1'));
00085 /**
00086  * Connects to the database using options in the given configuration array.
00087  *
00088  * @return boolean True if the database could be connected, else false
00089  */
00090     function connect() {
00091         $config = $this->config;
00092         $this->connected = false;
00093         $this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], $config['database'], $config['port']);
00094 
00095         if ($this->connection !== false) {
00096             $this->connected = true;
00097         }
00098 
00099         if (!empty($config['encoding'])) {
00100             $this->setEncoding($config['encoding']);
00101         }
00102         return $this->connected;
00103     }
00104 /**
00105  * Disconnects from database.
00106  *
00107  * @return boolean True if the database could be disconnected, else false
00108  */
00109     function disconnect() {
00110         @mysqli_free_result($this->results);
00111         $this->connected = !@mysqli_close($this->connection);
00112         return !$this->connected;
00113     }
00114 /**
00115  * Executes given SQL statement.
00116  *
00117  * @param string $sql SQL statement
00118  * @return resource Result resource identifier
00119  * @access protected
00120  */
00121     function _execute($sql) {
00122         return mysqli_query($this->connection, $sql);
00123     }
00124 /**
00125  * Returns an array of sources (tables) in the database.
00126  *
00127  * @return array Array of tablenames in the database
00128  */
00129     function listSources() {
00130         $cache = parent::listSources();
00131         if ($cache != null) {
00132             return $cache;
00133         }
00134         $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
00135 
00136         if (!$result) {
00137             return array();
00138         } else {
00139             $tables = array();
00140 
00141             while ($line = mysqli_fetch_array($result)) {
00142                 $tables[] = $line[0];
00143             }
00144             parent::listSources($tables);
00145             return $tables;
00146         }
00147     }
00148 /**
00149  * Returns an array of the fields in given table name.
00150  *
00151  * @param string $tableName Name of database table to inspect
00152  * @return array Fields in table. Keys are name and type
00153  */
00154     function describe(&$model) {
00155 
00156         $cache = parent::describe($model);
00157         if ($cache != null) {
00158             return $cache;
00159         }
00160 
00161         $fields = false;
00162         $cols = $this->query('DESCRIBE ' . $this->fullTableName($model));
00163 
00164         foreach ($cols as $column) {
00165             $colKey = array_keys($column);
00166             if (isset($column[$colKey[0]]) && !isset($column[0])) {
00167                 $column[0] = $column[$colKey[0]];
00168             }
00169             if (isset($column[0])) {
00170                 $fields[$column[0]['Field']] = array(
00171                     'type'      => $this->column($column[0]['Type']),
00172                     'null'      => ($column[0]['Null'] == 'YES' ? true : false),
00173                     'default'   => $column[0]['Default'],
00174                     'length'    => $this->length($column[0]['Type'])
00175                 );
00176             }
00177         }
00178 
00179         $this->__cacheDescription($this->fullTableName($model, false), $fields);
00180         return $fields;
00181     }
00182 /**
00183  * Returns a quoted and escaped string of $data for use in an SQL statement.
00184  *
00185  * @param string $data String to be prepared for use in an SQL statement
00186  * @param string $column The column into which this data will be inserted
00187  * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
00188  * @return string Quoted and escaped data
00189  */
00190     function value($data, $column = null, $safe = false) {
00191         $parent = parent::value($data, $column, $safe);
00192 
00193         if ($parent != null) {
00194             return $parent;
00195         }
00196 
00197         if ($data === null) {
00198             return 'NULL';
00199         }
00200 
00201         if ($data === '') {
00202             return  "''";
00203         }
00204 
00205         switch ($column) {
00206             case 'boolean':
00207                 $data = $this->boolean((bool)$data);
00208             break;
00209             case 'integer' :
00210             case 'float' :
00211             case null :
00212                 if (is_numeric($data) && strpos($data, ',') === false && $data[0] != '0' && strpos($data, 'e') === false) {
00213                     break;
00214                 }
00215             default:
00216                 $data = "'" . mysqli_real_escape_string($this->connection, $data) . "'";
00217             break;
00218         }
00219 
00220         return $data;
00221     }
00222 /**
00223  * Begin a transaction
00224  *
00225  * @param unknown_type $model
00226  * @return boolean True on success, false on fail
00227  * (i.e. if the database/model does not support transactions).
00228  */
00229     function begin(&$model) {
00230         if (parent::begin($model)) {
00231             if ($this->execute('START TRANSACTION')) {
00232                 $this->_transactionStarted = true;
00233                 return true;
00234             }
00235         }
00236         return false;
00237     }
00238 /**
00239  * Commit a transaction
00240  *
00241  * @param unknown_type $model
00242  * @return boolean True on success, false on fail
00243  * (i.e. if the database/model does not support transactions,
00244  * or a transaction has not started).
00245  */
00246     function commit(&$model) {
00247         if (parent::commit($model)) {
00248             $this->_transactionStarted = false;
00249             return $this->execute('COMMIT');
00250         }
00251         return false;
00252     }
00253 /**
00254  * Rollback a transaction
00255  *
00256  * @param unknown_type $model
00257  * @return boolean True on success, false on fail
00258  * (i.e. if the database/model does not support transactions,
00259  * or a transaction has not started).
00260  */
00261     function rollback(&$model) {
00262         if (parent::rollback($model)) {
00263             return $this->execute('ROLLBACK');
00264         }
00265         return false;
00266     }
00267 /**
00268  * Returns a formatted error message from previous database operation.
00269  *
00270  * @return string Error message with error number
00271  */
00272     function lastError() {
00273         if (mysqli_errno($this->connection)) {
00274             return mysqli_errno($this->connection).': '.mysqli_error($this->connection);
00275         }
00276         return null;
00277     }
00278 /**
00279  * Returns number of affected rows in previous database operation. If no previous operation exists,
00280  * this returns false.
00281  *
00282  * @return int Number of affected rows
00283  */
00284     function lastAffected() {
00285         if ($this->_result) {
00286             return mysqli_affected_rows($this->connection);
00287         }
00288         return null;
00289     }
00290 /**
00291  * Returns number of rows in previous resultset. If no previous resultset exists,
00292  * this returns false.
00293  *
00294  * @return int Number of rows in resultset
00295  */
00296     function lastNumRows() {
00297         if ($this->_result and is_object($this->_result)) {
00298             return @mysqli_num_rows($this->_result);
00299         }
00300         return null;
00301     }
00302 /**
00303  * Returns the ID generated from the previous INSERT operation.
00304  *
00305  * @param unknown_type $source
00306  * @return in
00307  */
00308     function lastInsertId($source = null) {
00309         $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
00310         if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
00311             return $id[0]['insertID'];
00312         }
00313 
00314         return null;
00315     }
00316 /**
00317  * Converts database-layer column types to basic types
00318  *
00319  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00320  * @return string Abstract column type (i.e. "string")
00321  */
00322     function column($real) {
00323         if (is_array($real)) {
00324             $col = $real['name'];
00325             if (isset($real['limit'])) {
00326                 $col .= '('.$real['limit'].')';
00327             }
00328             return $col;
00329         }
00330 
00331         $col = r(')', '', $real);
00332         $limit = $this->length($real);
00333         @list($col,$vals) = explode('(', $col);
00334 
00335         if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
00336             return $col;
00337         }
00338         if ($col == 'tinyint' && $limit == 1) {
00339             return 'boolean';
00340         }
00341         if (strpos($col, 'int') !== false) {
00342             return 'integer';
00343         }
00344         if (strpos($col, 'char') !== false || $col == 'tinytext') {
00345             return 'string';
00346         }
00347         if (strpos($col, 'text') !== false) {
00348             return 'text';
00349         }
00350         if (strpos($col, 'blob') !== false) {
00351             return 'binary';
00352         }
00353         if (in_array($col, array('float', 'double', 'decimal'))) {
00354             return 'float';
00355         }
00356         if (strpos($col, 'enum') !== false) {
00357             return "enum($vals)";
00358         }
00359         if ($col == 'boolean') {
00360             return $col;
00361         }
00362         return 'text';
00363     }
00364 /**
00365  * Gets the length of a database-native column description, or null if no length
00366  *
00367  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00368  * @return int An integer representing the length of the column
00369  */
00370     function length($real) {
00371         $col = r(array(')', 'unsigned'), '', $real);
00372         $limit = null;
00373 
00374         if (strpos($col, '(') !== false) {
00375             list($col, $limit) = explode('(', $col);
00376         }
00377 
00378         if ($limit != null) {
00379             return intval($limit);
00380         }
00381         return null;
00382     }
00383 /**
00384  * Enter description here...
00385  *
00386  * @param unknown_type $results
00387  */
00388     function resultSet(&$results) {
00389         $this->results =& $results;
00390         $this->map = array();
00391         $num_fields = mysqli_num_fields($results);
00392         $index = 0;
00393         $j = 0;
00394         while ($j < $num_fields) {
00395             $column = mysqli_fetch_field_direct($results, $j);
00396             if (!empty($column->table)) {
00397                 $this->map[$index++] = array($column->table, $column->name);
00398             } else {
00399                 $this->map[$index++] = array(0, $column->name);
00400             }
00401             $j++;
00402         }
00403     }
00404 /**
00405  * Fetches the next row from the current result set
00406  *
00407  * @return unknown
00408  */
00409     function fetchResult() {
00410         if ($row = mysqli_fetch_row($this->results)) {
00411             $resultRow = array();
00412             $i = 0;
00413             foreach ($row as $index => $field) {
00414                 @list($table, $column) = $this->map[$index];
00415                 $resultRow[$table][$column] = $row[$index];
00416                 $i++;
00417             }
00418             return $resultRow;
00419         } else {
00420             return false;
00421         }
00422     }
00423 /**
00424  * Sets the database encoding
00425  *
00426  * @param string $enc Database encoding
00427  * @return void
00428  */
00429     function setEncoding($enc) {
00430         return $this->_execute('SET NAMES ' . $enc) != false;
00431     }
00432 /**
00433  * Gets the database encoding
00434  *
00435  * @return string The database encoding
00436  */
00437     function getEncoding() {
00438         return mysqli_client_encoding($this->connection);
00439     }
00440 }
00441 ?>