]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/DB/mysqli.php
[ROUTES] Allow accept-header specification during router creation
[quix0rs-gnu-social.git] / extlib / DB / mysqli.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6  * The PEAR DB driver for PHP's mysqli extension
7  * for interacting with MySQL databases
8  *
9  * PHP version 5
10  *
11  * LICENSE: This source file is subject to version 3.0 of the PHP license
12  * that is available through the world-wide-web at the following URI:
13  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
14  * the PHP License and are unable to obtain it through the web, please
15  * send a note to license@php.net so we can mail you a copy immediately.
16  *
17  * @category   Database
18  * @package    DB
19  * @author     Daniel Convissor <danielc@php.net>
20  * @copyright  1997-2007 The PHP Group
21  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
22  * @version    CVS: $Id$
23  * @link       http://pear.php.net/package/DB
24  */
25
26 /**
27  * Obtain the DB_common class so it can be extended from
28  */
29 //require_once 'DB/common.php';
30 require_once 'common.php';
31
32 /**
33  * The methods PEAR DB uses to interact with PHP's mysqli extension
34  * for interacting with MySQL databases
35  *
36  * This is for MySQL versions 4.1 and above.  Requires PHP 5.
37  *
38  * Note that persistent connections no longer exist.
39  *
40  * These methods overload the ones declared in DB_common.
41  *
42  * @category   Database
43  * @package    DB
44  * @author     Daniel Convissor <danielc@php.net>
45  * @copyright  1997-2007 The PHP Group
46  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
47  * @version    Release: 1.9.2
48  * @link       http://pear.php.net/package/DB
49  * @since      Class functional since Release 1.6.3
50  */
51 class DB_mysqli extends DB_common
52 {
53     // {{{ properties
54
55     /**
56      * The DB driver type (mysql, oci8, odbc, etc.)
57      * @var string
58      */
59     public $phptype = 'mysqli';
60
61     /**
62      * The database syntax variant to be used (db2, access, etc.), if any
63      * @var string
64      */
65     public $dbsyntax = 'mysqli';
66
67     /**
68      * The capabilities of this DB implementation
69      *
70      * The 'new_link' element contains the PHP version that first provided
71      * new_link support for this DBMS.  Contains false if it's unsupported.
72      *
73      * Meaning of the 'limit' element:
74      *   + 'emulate' = emulate with fetch row by number
75      *   + 'alter'   = alter the query
76      *   + false     = skip rows
77      *
78      * @var array
79      */
80     public $features = array(
81         'limit' => 'alter',
82         'new_link' => false,
83         'numrows' => true,
84         'pconnect' => false,
85         'prepare' => false,
86         'ssl' => true,
87         'transactions' => true,
88     );
89
90     /**
91      * A mapping of native error codes to DB error codes
92      * @var array
93      */
94     public $errorcode_map = array(
95         1004 => DB_ERROR_CANNOT_CREATE,
96         1005 => DB_ERROR_CANNOT_CREATE,
97         1006 => DB_ERROR_CANNOT_CREATE,
98         1007 => DB_ERROR_ALREADY_EXISTS,
99         1008 => DB_ERROR_CANNOT_DROP,
100         1022 => DB_ERROR_ALREADY_EXISTS,
101         1044 => DB_ERROR_ACCESS_VIOLATION,
102         1046 => DB_ERROR_NODBSELECTED,
103         1048 => DB_ERROR_CONSTRAINT,
104         1049 => DB_ERROR_NOSUCHDB,
105         1050 => DB_ERROR_ALREADY_EXISTS,
106         1051 => DB_ERROR_NOSUCHTABLE,
107         1054 => DB_ERROR_NOSUCHFIELD,
108         1061 => DB_ERROR_ALREADY_EXISTS,
109         1062 => DB_ERROR_ALREADY_EXISTS,
110         1064 => DB_ERROR_SYNTAX,
111         1091 => DB_ERROR_NOT_FOUND,
112         1100 => DB_ERROR_NOT_LOCKED,
113         1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
114         1142 => DB_ERROR_ACCESS_VIOLATION,
115         1146 => DB_ERROR_NOSUCHTABLE,
116         1216 => DB_ERROR_CONSTRAINT,
117         1217 => DB_ERROR_CONSTRAINT,
118         1356 => DB_ERROR_DIVZERO,
119         1451 => DB_ERROR_CONSTRAINT,
120         1452 => DB_ERROR_CONSTRAINT,
121     );
122
123     /**
124      * The raw database connection created by PHP
125      * @var resource
126      */
127     public $connection;
128
129     /**
130      * The DSN information for connecting to a database
131      * @var array
132      */
133     public $dsn = array();
134
135
136     /**
137      * Should data manipulation queries be committed automatically?
138      * @var bool
139      * @access private
140      */
141     public $autocommit = true;
142
143     /**
144      * The quantity of transactions begun
145      *
146      * {@internal  While this is private, it can't actually be designated
147      * private in PHP 5 because it is directly accessed in the test suite.}}
148      *
149      * @var integer
150      * @access private
151      */
152     public $transaction_opcount = 0;
153
154     /**
155      * The database specified in the DSN
156      *
157      * It's a fix to allow calls to different databases in the same script.
158      *
159      * @var string
160      * @access private
161      */
162     public $_db = '';
163
164     /**
165      * Array for converting MYSQLI_*_FLAG constants to text values
166      * @var    array
167      * @access public
168      * @since  Property available since Release 1.6.5
169      */
170     public $mysqli_flags = array(
171         MYSQLI_NOT_NULL_FLAG => 'not_null',
172         MYSQLI_PRI_KEY_FLAG => 'primary_key',
173         MYSQLI_UNIQUE_KEY_FLAG => 'unique_key',
174         MYSQLI_MULTIPLE_KEY_FLAG => 'multiple_key',
175         MYSQLI_BLOB_FLAG => 'blob',
176         MYSQLI_UNSIGNED_FLAG => 'unsigned',
177         MYSQLI_ZEROFILL_FLAG => 'zerofill',
178         MYSQLI_AUTO_INCREMENT_FLAG => 'auto_increment',
179         MYSQLI_TIMESTAMP_FLAG => 'timestamp',
180         MYSQLI_SET_FLAG => 'set',
181         // MYSQLI_NUM_FLAG             => 'numeric',  // unnecessary
182         // MYSQLI_PART_KEY_FLAG        => 'multiple_key',  // duplicatvie
183         MYSQLI_GROUP_FLAG => 'group_by'
184     );
185
186     /**
187      * Array for converting MYSQLI_TYPE_* constants to text values
188      * @var    array
189      * @access public
190      * @since  Property available since Release 1.6.5
191      */
192     public $mysqli_types = array(
193         MYSQLI_TYPE_DECIMAL => 'decimal',
194         MYSQLI_TYPE_TINY => 'tinyint',
195         MYSQLI_TYPE_SHORT => 'int',
196         MYSQLI_TYPE_LONG => 'int',
197         MYSQLI_TYPE_FLOAT => 'float',
198         MYSQLI_TYPE_DOUBLE => 'double',
199         // MYSQLI_TYPE_NULL        => 'DEFAULT NULL',  // let flags handle it
200         MYSQLI_TYPE_TIMESTAMP => 'timestamp',
201         MYSQLI_TYPE_LONGLONG => 'bigint',
202         MYSQLI_TYPE_INT24 => 'mediumint',
203         MYSQLI_TYPE_DATE => 'date',
204         MYSQLI_TYPE_TIME => 'time',
205         MYSQLI_TYPE_DATETIME => 'datetime',
206         MYSQLI_TYPE_YEAR => 'year',
207         MYSQLI_TYPE_NEWDATE => 'date',
208         MYSQLI_TYPE_ENUM => 'enum',
209         MYSQLI_TYPE_SET => 'set',
210         MYSQLI_TYPE_TINY_BLOB => 'tinyblob',
211         MYSQLI_TYPE_MEDIUM_BLOB => 'mediumblob',
212         MYSQLI_TYPE_LONG_BLOB => 'longblob',
213         MYSQLI_TYPE_BLOB => 'blob',
214         MYSQLI_TYPE_VAR_STRING => 'varchar',
215         MYSQLI_TYPE_STRING => 'char',
216         MYSQLI_TYPE_GEOMETRY => 'geometry',
217         /* These constants are conditionally compiled in ext/mysqli, so we'll
218          * define them by number rather than constant. */
219         16 => 'bit',
220         246 => 'decimal',
221     );
222
223
224     // }}}
225     // {{{ constructor
226
227     /**
228      * This constructor calls <kbd>parent::__construct()</kbd>
229      *
230      * @return void
231      */
232     public function __construct()
233     {
234         parent::__construct();
235     }
236
237     // }}}
238     // {{{ connect()
239
240     /**
241      * Connect to the database server, log in and open the database
242      *
243      * Don't call this method directly.  Use DB::connect() instead.
244      *
245      * PEAR DB's mysqli driver supports the following extra DSN options:
246      *   + When the 'ssl' $option passed to DB::connect() is true:
247      *     + key      The path to the key file.
248      *     + cert     The path to the certificate file.
249      *     + ca       The path to the certificate authority file.
250      *     + capath   The path to a directory that contains trusted SSL
251      *                 CA certificates in pem format.
252      *     + cipher   The list of allowable ciphers for SSL encryption.
253      *
254      * Example of how to connect using SSL:
255      * <code>
256      * require_once 'DB.php';
257      *
258      * $dsn = array(
259      *     'phptype'  => 'mysqli',
260      *     'username' => 'someuser',
261      *     'password' => 'apasswd',
262      *     'hostspec' => 'localhost',
263      *     'database' => 'thedb',
264      *     'key'      => 'client-key.pem',
265      *     'cert'     => 'client-cert.pem',
266      *     'ca'       => 'cacert.pem',
267      *     'capath'   => '/path/to/ca/dir',
268      *     'cipher'   => 'AES',
269      * );
270      *
271      * $options = array(
272      *     'ssl' => true,
273      * );
274      *
275      * $db = DB::connect($dsn, $options);
276      * if ((new PEAR)->isError($db)) {
277      *     die($db->getMessage());
278      * }
279      * </code>
280      *
281      * @param array $dsn the data source name
282      * @param bool $persistent should the connection be persistent?
283      *
284      * @return int|object
285      */
286     public function connect($dsn, $persistent = false)
287     {
288         if (!PEAR::loadExtension('mysqli')) {
289             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
290         }
291
292         $this->dsn = $dsn;
293         if ($dsn['dbsyntax']) {
294             $this->dbsyntax = $dsn['dbsyntax'];
295         }
296
297         $ini = ini_get('track_errors');
298         @ini_set('track_errors', 1);
299         $php_errormsg = '';
300
301         if (((int)$this->getOption('ssl')) === 1) {
302             $init = mysqli_init();
303             mysqli_ssl_set(
304                 $init,
305                 empty($dsn['key']) ? null : $dsn['key'],
306                 empty($dsn['cert']) ? null : $dsn['cert'],
307                 empty($dsn['ca']) ? null : $dsn['ca'],
308                 empty($dsn['capath']) ? null : $dsn['capath'],
309                 empty($dsn['cipher']) ? null : $dsn['cipher']
310             );
311             if ($this->connection = @mysqli_real_connect(
312                 $init,
313                 $dsn['hostspec'],
314                 $dsn['username'],
315                 $dsn['password'],
316                 $dsn['database'],
317                 $dsn['port'],
318                 $dsn['socket']
319             )) {
320                 $this->connection = $init;
321             }
322         } else {
323             $this->connection = @mysqli_connect(
324                 $dsn['hostspec'],
325                 $dsn['username'],
326                 $dsn['password'],
327                 $dsn['database'],
328                 $dsn['port'],
329                 $dsn['socket']
330             );
331         }
332
333         @ini_set('track_errors', $ini);
334
335         if (!$this->connection) {
336             if (($err = @mysqli_connect_error()) != '') {
337                 return $this->raiseError(
338                     DB_ERROR_CONNECT_FAILED,
339                     null,
340                     null,
341                     null,
342                     $err
343                 );
344             } else {
345                 return $this->raiseError(
346                     DB_ERROR_CONNECT_FAILED,
347                     null,
348                     null,
349                     null,
350                     $php_errormsg
351                 );
352             }
353         }
354
355         if ($dsn['database']) {
356             $this->_db = $dsn['database'];
357         }
358
359         return DB_OK;
360     }
361
362     // }}}
363     // {{{ disconnect()
364
365     /**
366      * Disconnects from the database server
367      *
368      * @return bool  TRUE on success, FALSE on failure
369      */
370     public function disconnect()
371     {
372         $ret = @mysqli_close($this->connection);
373         $this->connection = null;
374         return $ret;
375     }
376
377     // }}}
378     // {{{ simpleQuery()
379
380     /**
381      * Sends a query to the database server
382      *
383      * @param string  the SQL query string
384      *
385      * @return mixed  + a PHP result resrouce for successful SELECT queries
386      *                + the DB_OK constant for other successful queries
387      *                + a DB_Error object on failure
388      */
389     public function simpleQuery($query)
390     {
391         $ismanip = $this->_checkManip($query);
392         $this->last_query = $query;
393         $query = $this->modifyQuery($query);
394         if ($this->_db) {
395             if (!@mysqli_select_db($this->connection, $this->_db)) {
396                 return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
397             }
398         }
399         if (!$this->autocommit && $ismanip) {
400             if ($this->transaction_opcount == 0) {
401                 $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=0');
402                 $result = @mysqli_query($this->connection, 'BEGIN');
403                 if (!$result) {
404                     return $this->mysqliRaiseError();
405                 }
406             }
407             $this->transaction_opcount++;
408         }
409         $result = @mysqli_query($this->connection, $query);
410         if (!$result) {
411             return $this->mysqliRaiseError();
412         }
413         if (is_object($result)) {
414             return $result;
415         }
416         return DB_OK;
417     }
418
419     // }}}
420     // {{{ nextResult()
421
422     /**
423      * Produces a DB_Error object regarding the current problem
424      *
425      * @param int $errno if the error is being manually raised pass a
426      *                     DB_ERROR* constant here.  If this isn't passed
427      *                     the error information gathered from the DBMS.
428      *
429      * @return object  the DB_Error object
430      *
431      * @see DB_common::raiseError(),
432      *      DB_mysqli::errorNative(), DB_common::errorCode()
433      */
434     public function mysqliRaiseError($errno = null)
435     {
436         if ($errno === null) {
437             if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
438                 $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
439                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
440                 $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
441             } else {
442                 // Doing this in case mode changes during runtime.
443                 $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
444                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
445                 $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
446             }
447             $errno = $this->errorCode(mysqli_errno($this->connection));
448         }
449         return $this->raiseError(
450             $errno,
451             null,
452             null,
453             null,
454             @mysqli_errno($this->connection) . ' ** ' .
455             @mysqli_error($this->connection)
456         );
457     }
458
459     // }}}
460     // {{{ fetchInto()
461
462     /**
463      * Move the internal mysql result pointer to the next available result.
464      *
465      * This method has not been implemented yet.
466      *
467      * @param resource $result a valid sql result resource
468      * @return false
469      * @access public
470      */
471     public function nextResult($result)
472     {
473         return false;
474     }
475
476     // }}}
477     // {{{ freeResult()
478
479     /**
480      * Places a row from the result set into the given array
481      *
482      * Formating of the array and the data therein are configurable.
483      * See DB_result::fetchInto() for more information.
484      *
485      * This method is not meant to be called directly.  Use
486      * DB_result::fetchInto() instead.  It can't be declared "protected"
487      * because DB_result is a separate object.
488      *
489      * @param resource $result the query result resource
490      * @param array $arr the referenced array to put the data in
491      * @param int $fetchmode how the resulting array should be indexed
492      * @param int $rownum the row number to fetch (0 = first row)
493      *
494      * @return mixed  DB_OK on success, NULL when the end of a result set is
495      *                 reached or on failure
496      *
497      * @see DB_result::fetchInto()
498      */
499     public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
500     {
501         if ($rownum !== null) {
502             if (!@mysqli_data_seek($result, $rownum)) {
503                 return null;
504             }
505         }
506         if ($fetchmode & DB_FETCHMODE_ASSOC) {
507             $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC);
508             if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
509                 $arr = array_change_key_case($arr, CASE_LOWER);
510             }
511         } else {
512             $arr = @mysqli_fetch_row($result);
513         }
514         if (!$arr) {
515             return null;
516         }
517         if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
518             /*
519              * Even though this DBMS already trims output, we do this because
520              * a field might have intentional whitespace at the end that
521              * gets removed by DB_PORTABILITY_RTRIM under another driver.
522              */
523             $this->_rtrimArrayValues($arr);
524         }
525         if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
526             $this->_convertNullArrayValuesToEmpty($arr);
527         }
528         return DB_OK;
529     }
530
531     // }}}
532     // {{{ numCols()
533
534     /**
535      * Deletes the result set and frees the memory occupied by the result set
536      *
537      * This method is not meant to be called directly.  Use
538      * DB_result::free() instead.  It can't be declared "protected"
539      * because DB_result is a separate object.
540      *
541      * @param resource $result PHP's query result resource
542      *
543      * @return bool  TRUE on success, FALSE if $result is invalid
544      *
545      * @see DB_result::free()
546      */
547     public function freeResult($result)
548     {
549         if (!$result instanceof mysqli_result) {
550             return false;
551         }
552         mysqli_free_result($result);
553         return true;
554     }
555
556     // }}}
557     // {{{ numRows()
558
559     /**
560      * Gets the number of columns in a result set
561      *
562      * This method is not meant to be called directly.  Use
563      * DB_result::numCols() instead.  It can't be declared "protected"
564      * because DB_result is a separate object.
565      *
566      * @param resource $result PHP's query result resource
567      *
568      * @return int|object
569      *
570      * @see DB_result::numCols()
571      */
572     public function numCols($result)
573     {
574         $cols = @mysqli_num_fields($result);
575         if (!$cols) {
576             return $this->mysqliRaiseError();
577         }
578         return $cols;
579     }
580
581     // }}}
582     // {{{ autoCommit()
583
584     /**
585      * Gets the number of rows in a result set
586      *
587      * This method is not meant to be called directly.  Use
588      * DB_result::numRows() instead.  It can't be declared "protected"
589      * because DB_result is a separate object.
590      *
591      * @param resource $result PHP's query result resource
592      *
593      * @return int|object
594      *
595      * @see DB_result::numRows()
596      */
597     public function numRows($result)
598     {
599         $rows = @mysqli_num_rows($result);
600         if ($rows === null) {
601             return $this->mysqliRaiseError();
602         }
603         return $rows;
604     }
605
606     // }}}
607     // {{{ commit()
608
609     /**
610      * Enables or disables automatic commits
611      *
612      * @param bool $onoff true turns it on, false turns it off
613      *
614      * @return int  DB_OK on success.  A DB_Error object if the driver
615      *               doesn't support auto-committing transactions.
616      */
617     public function autoCommit($onoff = false)
618     {
619         // XXX if $this->transaction_opcount > 0, we should probably
620         // issue a warning here.
621         $this->autocommit = $onoff ? true : false;
622         return DB_OK;
623     }
624
625     // }}}
626     // {{{ rollback()
627
628     /**
629      * Commits the current transaction
630      *
631      * @return int|object
632      */
633     public function commit()
634     {
635         if ($this->transaction_opcount > 0) {
636             if ($this->_db) {
637                 if (!@mysqli_select_db($this->connection, $this->_db)) {
638                     return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
639                 }
640             }
641             $result = @mysqli_query($this->connection, 'COMMIT');
642             $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1');
643             $this->transaction_opcount = 0;
644             if (!$result) {
645                 return $this->mysqliRaiseError();
646             }
647         }
648         return DB_OK;
649     }
650
651     // }}}
652     // {{{ affectedRows()
653
654     /**
655      * Reverts the current transaction
656      *
657      * @return int|object
658      */
659     public function rollback()
660     {
661         if ($this->transaction_opcount > 0) {
662             if ($this->_db) {
663                 if (!@mysqli_select_db($this->connection, $this->_db)) {
664                     return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
665                 }
666             }
667             $result = @mysqli_query($this->connection, 'ROLLBACK');
668             $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1');
669             $this->transaction_opcount = 0;
670             if (!$result) {
671                 return $this->mysqliRaiseError();
672             }
673         }
674         return DB_OK;
675     }
676
677     // }}}
678     // {{{ nextId()
679
680     /**
681      * Determines the number of rows affected by a data maniuplation query
682      *
683      * 0 is returned for queries that don't manipulate data.
684      *
685      * @return int  the number of rows.  A DB_Error object on failure.
686      */
687     public function affectedRows()
688     {
689         if ($this->_last_query_manip) {
690             return @mysqli_affected_rows($this->connection);
691         } else {
692             return 0;
693         }
694     }
695
696     /**
697      * Returns the next free id in a sequence
698      *
699      * @param string $seq_name name of the sequence
700      * @param boolean $ondemand when true, the seqence is automatically
701      *                            created if it does not exist
702      *
703      * @return int|object
704      *               A DB_Error object on failure.
705      *
706      * @see DB_common::nextID(), DB_common::getSequenceName(),
707      *      DB_mysqli::createSequence(), DB_mysqli::dropSequence()
708      */
709     public function nextId($seq_name, $ondemand = true)
710     {
711         $seqname = $this->getSequenceName($seq_name);
712         do {
713             $repeat = 0;
714             $this->pushErrorHandling(PEAR_ERROR_RETURN);
715             $result = $this->query('UPDATE ' . $seqname
716                 . ' SET id = LAST_INSERT_ID(id + 1)');
717             $this->popErrorHandling();
718             if ($result === DB_OK) {
719                 // COMMON CASE
720                 $id = @mysqli_insert_id($this->connection);
721                 if ($id != 0) {
722                     return $id;
723                 }
724
725                 // EMPTY SEQ TABLE
726                 // Sequence table must be empty for some reason,
727                 // so fill it and return 1
728                 // Obtain a user-level lock
729                 $result = $this->getOne('SELECT GET_LOCK('
730                     . "'${seqname}_lock', 10)");
731                 if (DB::isError($result)) {
732                     return $this->raiseError($result);
733                 }
734                 if ($result == 0) {
735                     return $this->mysqliRaiseError(DB_ERROR_NOT_LOCKED);
736                 }
737
738                 // add the default value
739                 $result = $this->query('REPLACE INTO ' . $seqname
740                     . ' (id) VALUES (0)');
741                 if (DB::isError($result)) {
742                     return $this->raiseError($result);
743                 }
744
745                 // Release the lock
746                 $result = $this->getOne('SELECT RELEASE_LOCK('
747                     . "'${seqname}_lock')");
748                 if (DB::isError($result)) {
749                     return $this->raiseError($result);
750                 }
751                 // We know what the result will be, so no need to try again
752                 return 1;
753             } elseif ($ondemand && DB::isError($result) &&
754                 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
755                 // ONDEMAND TABLE CREATION
756                 $result = $this->createSequence($seq_name);
757
758                 // Since createSequence initializes the ID to be 1,
759                 // we do not need to retrieve the ID again (or we will get 2)
760                 if (DB::isError($result)) {
761                     return $this->raiseError($result);
762                 } else {
763                     // First ID of a newly created sequence is 1
764                     return 1;
765                 }
766             } elseif (DB::isError($result) &&
767                 $result->getCode() == DB_ERROR_ALREADY_EXISTS) {
768                 // BACKWARDS COMPAT
769                 // see _BCsequence() comment
770                 $result = $this->_BCsequence($seqname);
771                 if (DB::isError($result)) {
772                     return $this->raiseError($result);
773                 }
774                 $repeat = 1;
775             }
776         } while ($repeat);
777
778         return $this->raiseError($result);
779     }
780
781     // }}}
782     // {{{ dropSequence()
783
784     /**
785      * Creates a new sequence
786      *
787      * @param string $seq_name name of the new sequence
788      *
789      * @return int  DB_OK on success.  A DB_Error object on failure.
790      *
791      * @see DB_common::createSequence(), DB_common::getSequenceName(),
792      *      DB_mysqli::nextID(), DB_mysqli::dropSequence()
793      */
794     public function createSequence($seq_name)
795     {
796         $seqname = $this->getSequenceName($seq_name);
797         $res = $this->query('CREATE TABLE ' . $seqname
798             . ' (id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'
799             . ' PRIMARY KEY(id))');
800         if (DB::isError($res)) {
801             return $res;
802         }
803         // insert yields value 1, nextId call will generate ID 2
804         return $this->query("INSERT INTO ${seqname} (id) VALUES (0)");
805     }
806
807     // }}}
808     // {{{ _BCsequence()
809
810     /**
811      * Backwards compatibility with old sequence emulation implementation
812      * (clean up the dupes)
813      *
814      * @param string $seqname the sequence name to clean up
815      *
816      * @return bool|object
817      *
818      * @access private
819      */
820     public function _BCsequence($seqname)
821     {
822         // Obtain a user-level lock... this will release any previous
823         // application locks, but unlike LOCK TABLES, it does not abort
824         // the current transaction and is much less frequently used.
825         $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
826         if (DB::isError($result)) {
827             return $result;
828         }
829         if ($result == 0) {
830             // Failed to get the lock, can't do the conversion, bail
831             // with a DB_ERROR_NOT_LOCKED error
832             return $this->mysqliRaiseError(DB_ERROR_NOT_LOCKED);
833         }
834
835         $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
836         if (DB::isError($highest_id)) {
837             return $highest_id;
838         }
839
840         // This should kill all rows except the highest
841         // We should probably do something if $highest_id isn't
842         // numeric, but I'm at a loss as how to handle that...
843         $result = $this->query('DELETE FROM ' . $seqname
844             . " WHERE id <> $highest_id");
845         if (DB::isError($result)) {
846             return $result;
847         }
848
849         // If another thread has been waiting for this lock,
850         // it will go thru the above procedure, but will have no
851         // real effect
852         $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
853         if (DB::isError($result)) {
854             return $result;
855         }
856         return true;
857     }
858
859     // }}}
860     // {{{ quoteIdentifier()
861
862     /**
863      * Deletes a sequence
864      *
865      * @param string $seq_name name of the sequence to be deleted
866      *
867      * @return int  DB_OK on success.  A DB_Error object on failure.
868      *
869      * @see DB_common::dropSequence(), DB_common::getSequenceName(),
870      *      DB_mysql::nextID(), DB_mysql::createSequence()
871      */
872     public function dropSequence($seq_name)
873     {
874         return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
875     }
876
877     // }}}
878     // {{{ escapeSimple()
879
880     /**
881      * Quotes a string so it can be safely used as a table or column name
882      * (WARNING: using names that require this is a REALLY BAD IDEA)
883      *
884      * WARNING:  Older versions of MySQL can't handle the backtick
885      * character (<kbd>`</kbd>) in table or column names.
886      *
887      * @param string $str identifier name to be quoted
888      *
889      * @return string  quoted identifier string
890      *
891      * @see DB_common::quoteIdentifier()
892      * @since Method available since Release 1.6.0
893      */
894     public function quoteIdentifier($str)
895     {
896         return '`' . str_replace('`', '``', $str) . '`';
897     }
898
899     // }}}
900     // {{{ modifyLimitQuery()
901
902     /**
903      * Escapes a string according to the current DBMS's standards
904      *
905      * @param string $str the string to be escaped
906      *
907      * @return string  the escaped string
908      *
909      * @see DB_common::quoteSmart()
910      * @since Method available since Release 1.6.0
911      */
912     public function escapeSimple($str)
913     {
914         return @mysqli_real_escape_string($this->connection, $str);
915     }
916
917     // }}}
918     // {{{ mysqliRaiseError()
919
920     /**
921      * Adds LIMIT clauses to a query string according to current DBMS standards
922      *
923      * @param string $query the query to modify
924      * @param int $from the row to start to fetching (0 = the first row)
925      * @param int $count the numbers of rows to fetch
926      * @param mixed $params array, string or numeric data to be used in
927      *                         execution of the statement.  Quantity of items
928      *                         passed must match quantity of placeholders in
929      *                         query:  meaning 1 placeholder for non-array
930      *                         parameters or 1 placeholder per array element.
931      *
932      * @return string  the query string with LIMIT clauses added
933      *
934      * @access protected
935      */
936     public function modifyLimitQuery($query, $from, $count, $params = array())
937     {
938         if (DB::isManip($query) || $this->_next_query_manip) {
939             return $query . " LIMIT $count";
940         } else {
941             return $query . " LIMIT $from, $count";
942         }
943     }
944
945     // }}}
946     // {{{ errorNative()
947
948     /**
949      * Gets the DBMS' native error code produced by the last query
950      *
951      * @return int  the DBMS' error code
952      */
953     public function errorNative()
954     {
955         return @mysqli_errno($this->connection);
956     }
957
958     // }}}
959     // {{{ tableInfo()
960
961     /**
962      * Returns information about a table or a result set
963      *
964      * @param object|string $result DB_result object from a query or a
965      *                                 string containing the name of a table.
966      *                                 While this also accepts a query result
967      *                                 resource identifier, this behavior is
968      *                                 deprecated.
969      * @param int $mode a valid tableInfo mode
970      *
971      * @return array|object
972      *                 A DB_Error object on failure.
973      *
974      * @see DB_common::setOption()
975      */
976     public function tableInfo($result, $mode = null)
977     {
978         if (is_string($result)) {
979             // Fix for bug #11580.
980             if ($this->_db) {
981                 if (!@mysqli_select_db($this->connection, $this->_db)) {
982                     return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
983                 }
984             }
985
986             /*
987              * Probably received a table name.
988              * Create a result resource identifier.
989              */
990             $id = @mysqli_query(
991                 $this->connection,
992                 "SELECT * FROM $result LIMIT 0"
993             );
994             $got_string = true;
995         } elseif (isset($result->result)) {
996             /*
997              * Probably received a result object.
998              * Extract the result resource identifier.
999              */
1000             $id = $result->result;
1001             $got_string = false;
1002         } else {
1003             /*
1004              * Probably received a result resource identifier.
1005              * Copy it.
1006              * Deprecated.  Here for compatibility only.
1007              */
1008             $id = $result;
1009             $got_string = false;
1010         }
1011
1012         if (!is_object($id) || !is_a($id, 'mysqli_result')) {
1013             return $this->mysqliRaiseError(DB_ERROR_NEED_MORE_DATA);
1014         }
1015
1016         if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
1017             $case_func = 'strtolower';
1018         } else {
1019             $case_func = 'strval';
1020         }
1021
1022         $count = @mysqli_num_fields($id);
1023         $res = array();
1024
1025         if ($mode) {
1026             $res['num_fields'] = $count;
1027         }
1028
1029         for ($i = 0; $i < $count; $i++) {
1030             $tmp = @mysqli_fetch_field($id);
1031
1032             $flags = '';
1033             foreach ($this->mysqli_flags as $const => $means) {
1034                 if ($tmp->flags & $const) {
1035                     $flags .= $means . ' ';
1036                 }
1037             }
1038             if ($tmp->def) {
1039                 $flags .= 'default_' . rawurlencode($tmp->def);
1040             }
1041             $flags = trim($flags);
1042
1043             $res[$i] = array(
1044                 'table' => $case_func($tmp->table),
1045                 'name' => $case_func($tmp->name),
1046                 'type' => isset($this->mysqli_types[$tmp->type])
1047                     ? $this->mysqli_types[$tmp->type]
1048                     : 'unknown',
1049                 // http://bugs.php.net/?id=36579
1050                 //  Doc Bug #36579: mysqli_fetch_field length handling
1051                 // https://bugs.php.net/bug.php?id=62426
1052                 //  Bug #62426: mysqli_fetch_field_direct returns incorrect
1053                 //  length on UTF8 fields
1054                 'len' => $tmp->length,
1055                 'flags' => $flags,
1056             );
1057
1058             if ($mode & DB_TABLEINFO_ORDER) {
1059                 $res['order'][$res[$i]['name']] = $i;
1060             }
1061             if ($mode & DB_TABLEINFO_ORDERTABLE) {
1062                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
1063             }
1064         }
1065
1066         // free the result only if we were called on a table
1067         if ($got_string) {
1068             @mysqli_free_result($id);
1069         }
1070         return $res;
1071     }
1072
1073     // }}}
1074     // {{{ getSpecialQuery()
1075
1076     /**
1077      * Obtains the query string needed for listing a given type of objects
1078      *
1079      * @param string $type the kind of objects you want to retrieve
1080      *
1081      * @return string  the SQL query string or null if the driver doesn't
1082      *                  support the object type requested
1083      *
1084      * @access protected
1085      * @see DB_common::getListOf()
1086      */
1087     public function getSpecialQuery($type)
1088     {
1089         switch ($type) {
1090             case 'tables':
1091                 return 'SHOW TABLES';
1092             case 'users':
1093                 return 'SELECT DISTINCT User FROM mysql.user';
1094             case 'databases':
1095                 return 'SHOW DATABASES';
1096             default:
1097                 return null;
1098         }
1099     }
1100
1101     public function getVersion()
1102     {
1103         return mysqli_get_server_version($this->connection);
1104     }
1105
1106     // }}}
1107 }
1108
1109 /*
1110  * Local variables:
1111  * tab-width: 4
1112  * c-basic-offset: 4
1113  * End:
1114  */