2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license, |
9 // | that is bundled with this package in the file LICENSE, and is |
10 // | available at through the world-wide-web at |
11 // | http://www.php.net/license/2_02.txt. |
12 // | If you did not receive a copy of the PHP license and are unable to |
13 // | obtain it through the world-wide-web, please send a note to |
14 // | license@php.net so we can mail you a copy immediately. |
15 // +----------------------------------------------------------------------+
16 // | Author: Chaillan Nicolas <nicos@php.net> |
17 // | Based on mysql.php by Stig Bakken <ssb@php.net> |
18 // | Maintainer: Daniel Convissor <danielc@php.net> |
19 // +----------------------------------------------------------------------+
21 // NOTE: The tableInfo() method must be redone because the functions it
22 // relies on no longer exist in the new extension.
26 require_once 'DB/common.php';
29 * Database independent query interface definition for PHP's mysqli
32 * This is for MySQL versions 4.1 and above. Requires PHP 5.
34 * Note that persistent connections no longer exist.
39 * @author Chaillan Nicolas <nicos@php.net>
41 class DB_mysqli extends DB_common
46 var $phptype, $dbsyntax;
47 var $prepare_tokens = array();
48 var $prepare_types = array();
49 var $num_rows = array();
50 var $transaction_opcount = 0;
51 var $autocommit = true;
52 var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
59 * DB_mysql constructor.
66 $this->phptype = 'mysqli';
67 $this->dbsyntax = 'mysqli';
68 $this->features = array(
71 'transactions' => true,
74 $this->errorcode_map = array(
75 1004 => DB_ERROR_CANNOT_CREATE,
76 1005 => DB_ERROR_CANNOT_CREATE,
77 1006 => DB_ERROR_CANNOT_CREATE,
78 1007 => DB_ERROR_ALREADY_EXISTS,
79 1008 => DB_ERROR_CANNOT_DROP,
80 1022 => DB_ERROR_ALREADY_EXISTS,
81 1046 => DB_ERROR_NODBSELECTED,
82 1050 => DB_ERROR_ALREADY_EXISTS,
83 1051 => DB_ERROR_NOSUCHTABLE,
84 1054 => DB_ERROR_NOSUCHFIELD,
85 1062 => DB_ERROR_ALREADY_EXISTS,
86 1064 => DB_ERROR_SYNTAX,
87 1100 => DB_ERROR_NOT_LOCKED,
88 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
89 1146 => DB_ERROR_NOSUCHTABLE,
90 1048 => DB_ERROR_CONSTRAINT,
91 1216 => DB_ERROR_CONSTRAINT,
99 * Connect to a database and log in as the specified user.
101 * @param string $dsn the data source name (see DB::parseDSN for syntax)
102 * @param boolean $persistent (optional) whether the connection should
104 * @return mixed DB_OK on success, a DB error on failure
107 function connect($dsninfo, $persistent = false)
109 if (!DB::assertExtension('mysqli')) {
110 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
113 $this->dsn = $dsninfo;
114 if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') {
115 $dbhost = ':' . $dsninfo['socket'];
117 $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
118 if ($dsninfo['port']) {
119 $dbhost .= ':' . $dsninfo['port'];
123 $ssl_mode = $this->getOption('ssl') === true ? 'CLIENT_SSL' : NULL;
125 @ini_set('track_errors', true);
127 if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
128 // Need to verify if arguments are okay
129 $conn = @mysqli_connect($dbhost, $dsninfo['username'],
130 $dsninfo['password'], $ssl_mode);
131 } elseif ($dbhost && isset($dsninfo['username'])) {
132 $conn = @mysqli_connect($dbhost, $dsninfo['username'], null,
135 $conn = @mysqli_connect($dbhost, null, null, $ssl_mode);
140 @ini_restore('track_errors');
143 if (($err = @mysqli_error()) != '') {
144 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
146 } elseif (empty($php_errormsg)) {
147 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
149 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
150 null, $php_errormsg);
154 if ($dsninfo['database']) {
155 if (!@mysqli_select_db($dsninfo['database'], $conn)) {
156 switch(mysqli_errno($conn)) {
158 return $this->raiseError(DB_ERROR_NOSUCHDB, null, null,
159 null, @mysqli_error($conn));
161 return $this->raiseError(DB_ERROR_ACCESS_VIOLATION, null, null,
162 null, @mysqli_error($conn));
164 return $this->raiseError(DB_ERROR, null, null,
165 null, @mysqli_error($conn));
168 // fix to allow calls to different databases in the same script
169 $this->_db = $dsninfo['database'];
172 $this->connection = $conn;
180 * Log out and disconnect from the database.
182 * @return boolean true on success, false if not connected
185 function disconnect()
187 $ret = @mysqli_close($this->connection);
188 $this->connection = null;
196 * Send a query to MySQL and return the results as a MySQL resource
199 * @param string $query the SQL query
200 * @return mixed a valid MySQL result for successful SELECT
201 * queries, DB_OK for other successful queries.
202 * A DB error is returned on failure.
205 function simpleQuery($query)
207 $ismanip = DB::isManip($query);
208 $this->last_query = $query;
209 $query = $this->modifyQuery($query);
211 if (!@mysqli_select_db($this->_db, $this->connection)) {
212 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
215 if (!$this->autocommit && $ismanip) {
216 if ($this->transaction_opcount == 0) {
217 $result = @mysqli_query('SET AUTOCOMMIT=0', $this->connection);
218 $result = @mysqli_query('BEGIN', $this->connection);
220 return $this->mysqlRaiseError();
223 $this->transaction_opcount++;
225 $result = @mysqli_query($query, $this->connection);
227 return $this->mysqlRaiseError();
229 if (is_resource($result)) {
230 $numrows = $this->numrows($result);
231 if (is_object($numrows)) {
234 $this->num_rows[(int)$result] = $numrows;
244 * Move the internal mysql result pointer to the next available result.
246 * This method has not been implemented yet.
248 * @param resource $result a valid sql result resource
252 function nextResult($result)
261 * Fetch a row and insert the data into an existing array.
263 * Formating of the array and the data therein are configurable.
264 * See DB_result::fetchInto() for more information.
266 * @param resource $result query result identifier
267 * @param array $arr (reference) array where data from the row
269 * @param int $fetchmode how the resulting array should be indexed
270 * @param int $rownum the row number to fetch
272 * @return mixed DB_OK on success, null when end of result set is
273 * reached or on failure
275 * @see DB_result::fetchInto()
278 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
280 if ($rownum !== null) {
281 if (!@mysqli_data_seek($result, $rownum)) {
285 if ($fetchmode & DB_FETCHMODE_ASSOC) {
286 $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC);
287 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
288 $arr = array_change_key_case($arr, CASE_LOWER);
291 $arr = @mysqli_fetch_row($result);
294 $errno = @mysqli_errno($this->connection);
298 return $this->mysqlRaiseError($errno);
300 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
302 * Even though this DBMS already trims output, we do this because
303 * a field might have intentional whitespace at the end that
304 * gets removed by DB_PORTABILITY_RTRIM under another driver.
306 $this->_rtrimArrayValues($arr);
308 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
309 $this->_convertNullArrayValuesToEmpty($arr);
318 * Free the internal resources associated with $result.
320 * @param resource $result MySQL result identifier
321 * @return bool true on success, false if $result is invalid
324 function freeResult($result)
326 unset($this->num_rows[(int)$result]);
327 return @mysqli_free_result($result);
334 * Get the number of columns in a result set.
336 * @param $result MySQL result identifier
340 * @return int the number of columns per row in $result
342 function numCols($result)
344 $cols = @mysqli_num_fields($result);
347 return $this->mysqlRaiseError();
357 * Get the number of rows in a result set.
359 * @param resource $result MySQL result identifier
360 * @return int the number of rows in $result
363 function numRows($result)
365 $rows = @mysqli_num_rows($result);
366 if ($rows === null) {
367 return $this->mysqlRaiseError();
376 * Enable/disable automatic commits.
378 function autoCommit($onoff = false)
380 // XXX if $this->transaction_opcount > 0, we should probably
381 // issue a warning here.
382 $this->autocommit = $onoff ? true : false;
390 * Commit the current transaction.
394 if ($this->transaction_opcount > 0) {
396 if (!@mysqli_select_db($this->_db, $this->connection)) {
397 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
400 $result = @mysqli_query('COMMIT', $this->connection);
401 $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
402 $this->transaction_opcount = 0;
404 return $this->mysqlRaiseError();
414 * Roll back (undo) the current transaction.
418 if ($this->transaction_opcount > 0) {
420 if (!@mysqli_select_db($this->_db, $this->connection)) {
421 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
424 $result = @mysqli_query('ROLLBACK', $this->connection);
425 $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
426 $this->transaction_opcount = 0;
428 return $this->mysqlRaiseError();
435 // {{{ affectedRows()
438 * Gets the number of rows affected by the data manipulation
439 * query. For other queries, this function returns 0.
441 * @return integer number of rows affected by the last query
443 function affectedRows()
445 if (DB::isManip($this->last_query)) {
446 return @mysqli_affected_rows($this->connection);
456 * Get the native error code of the last error (if any) that
457 * occured on the current connection.
459 * @return int native MySQL error code
462 function errorNative()
464 return @mysqli_errno($this->connection);
471 * Returns the next free id in a sequence
473 * @param string $seq_name name of the sequence
474 * @param boolean $ondemand when true, the seqence is automatically
475 * created if it does not exist
477 * @return int the next id number in the sequence. DB_Error if problem.
480 * @see DB_common::nextID()
483 function nextId($seq_name, $ondemand = true)
485 $seqname = $this->getSequenceName($seq_name);
488 $this->pushErrorHandling(PEAR_ERROR_RETURN);
489 $result = $this->query("UPDATE ${seqname} ".
490 'SET id=LAST_INSERT_ID(id+1)');
491 $this->popErrorHandling();
492 if ($result == DB_OK) {
494 $id = @mysqli_insert_id($this->connection);
498 /** EMPTY SEQ TABLE **/
499 // Sequence table must be empty for some reason, so fill it and return 1
500 // Obtain a user-level lock
501 $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
502 if (DB::isError($result)) {
503 return $this->raiseError($result);
506 // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error
507 return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
510 // add the default value
511 $result = $this->query("REPLACE INTO ${seqname} VALUES (0)");
512 if (DB::isError($result)) {
513 return $this->raiseError($result);
517 $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
518 if (DB::isError($result)) {
519 return $this->raiseError($result);
521 // We know what the result will be, so no need to try again
524 /** ONDEMAND TABLE CREATION **/
525 } elseif ($ondemand && DB::isError($result) &&
526 $result->getCode() == DB_ERROR_NOSUCHTABLE)
528 $result = $this->createSequence($seq_name);
529 // Since createSequence initializes the ID to be 1,
530 // we do not need to retrieve the ID again (or we will get 2)
531 if (DB::isError($result)) {
532 return $this->raiseError($result);
534 // First ID of a newly created sequence is 1
538 /** BACKWARDS COMPAT **/
539 } elseif (DB::isError($result) &&
540 $result->getCode() == DB_ERROR_ALREADY_EXISTS)
542 // see _BCsequence() comment
543 $result = $this->_BCsequence($seqname);
544 if (DB::isError($result)) {
545 return $this->raiseError($result);
551 return $this->raiseError($result);
555 * Creates a new sequence
557 * @param string $seq_name name of the new sequence
559 * @return int DB_OK on success. A DB_Error object is returned if
563 * @see DB_common::createSequence()
566 function createSequence($seq_name)
568 $seqname = $this->getSequenceName($seq_name);
569 $res = $this->query("CREATE TABLE ${seqname} ".
570 '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
571 ' PRIMARY KEY(id))');
572 if (DB::isError($res)) {
575 // insert yields value 1, nextId call will generate ID 2
576 return $this->query("INSERT INTO ${seqname} VALUES(0)");
580 // {{{ dropSequence()
585 * @param string $seq_name name of the sequence to be deleted
587 * @return int DB_OK on success. DB_Error if problems.
590 * @see DB_common::dropSequence()
593 function dropSequence($seq_name)
595 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
602 * Backwards compatibility with old sequence emulation implementation
603 * (clean up the dupes).
605 * @param string $seqname The sequence name to clean up
606 * @return mixed DB_Error or true
608 function _BCsequence($seqname)
610 // Obtain a user-level lock... this will release any previous
611 // application locks, but unlike LOCK TABLES, it does not abort
612 // the current transaction and is much less frequently used.
613 $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
614 if (DB::isError($result)) {
618 // Failed to get the lock, can't do the conversion, bail
619 // with a DB_ERROR_NOT_LOCKED error
620 return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
623 $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
624 if (DB::isError($highest_id)) {
627 // This should kill all rows except the highest
628 // We should probably do something if $highest_id isn't
629 // numeric, but I'm at a loss as how to handle that...
630 $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id");
631 if (DB::isError($result)) {
635 // If another thread has been waiting for this lock,
636 // it will go thru the above procedure, but will have no
638 $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
639 if (DB::isError($result)) {
646 // {{{ quoteIdentifier()
649 * Quote a string so it can be safely used as a table or column name
651 * Quoting style depends on which database driver is being used.
653 * MySQL can't handle the backtick character (<kbd>`</kbd>) in
654 * table or column names.
656 * @param string $str identifier name to be quoted
658 * @return string quoted identifier string
664 function quoteIdentifier($str)
666 return '`' . $str . '`';
670 // {{{ escapeSimple()
673 * Escape a string according to the current DBMS's standards
675 * @param string $str the string to be escaped
677 * @return string the escaped string
681 function escapeSimple($str) {
682 return @mysqli_real_escape_string($str, $this->connection);
688 function modifyQuery($query)
690 if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
691 // "DELETE FROM table" gives 0 affected rows in MySQL.
692 // This little hack lets you know how many rows were deleted.
693 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
694 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
695 'DELETE FROM \1 WHERE 1=1', $query);
702 // {{{ modifyLimitQuery()
704 function modifyLimitQuery($query, $from, $count)
706 if (DB::isManip($query)) {
707 return $query . " LIMIT $count";
709 return $query . " LIMIT $from, $count";
714 // {{{ mysqlRaiseError()
717 * Gather information about an error, then use that info to create a
718 * DB error object and finally return that object.
720 * @param integer $errno PEAR error number (usually a DB constant) if
721 * manually raising an error
722 * @return object DB error object
723 * @see DB_common::errorCode()
724 * @see DB_common::raiseError()
726 function mysqlRaiseError($errno = null)
728 if ($errno === null) {
729 if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
730 $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
731 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
732 $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
734 // Doing this in case mode changes during runtime.
735 $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
736 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
737 $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
739 $errno = $this->errorCode(mysqli_errno($this->connection));
741 return $this->raiseError($errno, null, null, null,
742 @mysqli_errno($this->connection) . ' ** ' .
743 @mysqli_error($this->connection));
750 * Returns information about a table or a result set.
752 * WARNING: this method will probably not work because the mysqli_*()
753 * functions it relies upon may not exist.
755 * @param object|string $result DB_result object from a query or a
756 * string containing the name of a table
757 * @param int $mode a valid tableInfo mode
758 * @return array an associative array with the information requested
759 * or an error object if something is wrong
762 * @see DB_common::tableInfo()
764 function tableInfo($result, $mode = null) {
765 if (isset($result->result)) {
767 * Probably received a result object.
768 * Extract the result resource identifier.
770 $id = $result->result;
772 } elseif (is_string($result)) {
774 * Probably received a table name.
775 * Create a result resource identifier.
777 $id = @mysqli_list_fields($this->dsn['database'],
778 $result, $this->connection);
782 * Probably received a result resource identifier.
784 * Depricated. Here for compatibility only.
790 if (!is_resource($id)) {
791 return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
794 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
795 $case_func = 'strtolower';
797 $case_func = 'strval';
800 $count = @mysqli_num_fields($id);
802 // made this IF due to performance (one if is faster than $count if's)
804 for ($i=0; $i<$count; $i++) {
805 $res[$i]['table'] = $case_func(@mysqli_field_table($id, $i));
806 $res[$i]['name'] = $case_func(@mysqli_field_name($id, $i));
807 $res[$i]['type'] = @mysqli_field_type($id, $i);
808 $res[$i]['len'] = @mysqli_field_len($id, $i);
809 $res[$i]['flags'] = @mysqli_field_flags($id, $i);
812 $res['num_fields']= $count;
814 for ($i=0; $i<$count; $i++) {
815 $res[$i]['table'] = $case_func(@mysqli_field_table($id, $i));
816 $res[$i]['name'] = $case_func(@mysqli_field_name($id, $i));
817 $res[$i]['type'] = @mysqli_field_type($id, $i);
818 $res[$i]['len'] = @mysqli_field_len($id, $i);
819 $res[$i]['flags'] = @mysqli_field_flags($id, $i);
821 if ($mode & DB_TABLEINFO_ORDER) {
822 $res['order'][$res[$i]['name']] = $i;
824 if ($mode & DB_TABLEINFO_ORDERTABLE) {
825 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
830 // free the result only if we were called on a table
832 @mysqli_free_result($id);
838 // {{{ getSpecialQuery()
841 * Returns the query needed to get some backend info.
843 * @param string $type What kind of info you want to retrieve
844 * @return string The SQL query string
846 function getSpecialQuery($type)
850 return 'SHOW TABLES';
852 return DB_ERROR_NOT_CAPABLE;
854 $sql = 'select distinct User from user';
855 if ($this->dsn['database'] != 'mysql') {
857 $dsn['database'] = 'mysql';
858 if (DB::isError($db = DB::connect($dsn))) {
861 $sql = $db->getCol($sql);
863 // XXX Fixme the mysql driver should take care of this
864 if (!@mysqli_select_db($this->dsn['database'], $this->connection)) {
865 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
870 return 'SHOW DATABASES';