]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/DB/mysqli.php
extra_empty_lines
[SourceForge/phpwiki.git] / lib / pear / DB / mysqli.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
4 // | PHP Version 4                                                        |
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 // +----------------------------------------------------------------------+
20 //
21 // $Id$
22
23 // NOTE:  The tableInfo() method must be redone because the functions it
24 // relies on no longer exist in the new extension.
25 //
26 // EXPERIMENTAL
27
28 require_once 'DB/common.php';
29
30 /**
31  * Database independent query interface definition for PHP's mysqli
32  * extension.
33  *
34  * This is for MySQL versions 4.1 and above.  Requires PHP 5.
35  *
36  * Note that persistent connections no longer exist.
37  *
38  * @package  DB
39  * @version  $Id$
40  * @category Database
41  * @author   Chaillan Nicolas <nicos@php.net>
42  */
43 class DB_mysqli extends DB_common
44 {
45     // {{{ properties
46
47     var $connection;
48     var $phptype, $dbsyntax;
49     var $prepare_tokens = array();
50     var $prepare_types = array();
51     var $num_rows = array();
52     var $transaction_opcount = 0;
53     var $autocommit = true;
54     var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
55     var $_db = false;
56
57     // }}}
58     // {{{ constructor
59
60     /**
61      * DB_mysql constructor.
62      *
63      * @access public
64      */
65     function DB_mysqli()
66     {
67         $this->DB_common();
68         $this->phptype = 'mysqli';
69         $this->dbsyntax = 'mysqli';
70         $this->features = array(
71             'prepare' => false,
72             'ssl' => true,
73             'transactions' => true,
74             'limit' => 'alter'
75         );
76         $this->errorcode_map = array(
77             1004 => DB_ERROR_CANNOT_CREATE,
78             1005 => DB_ERROR_CANNOT_CREATE,
79             1006 => DB_ERROR_CANNOT_CREATE,
80             1007 => DB_ERROR_ALREADY_EXISTS,
81             1008 => DB_ERROR_CANNOT_DROP,
82             1022 => DB_ERROR_ALREADY_EXISTS,
83             1046 => DB_ERROR_NODBSELECTED,
84             1050 => DB_ERROR_ALREADY_EXISTS,
85             1051 => DB_ERROR_NOSUCHTABLE,
86             1054 => DB_ERROR_NOSUCHFIELD,
87             1062 => DB_ERROR_ALREADY_EXISTS,
88             1064 => DB_ERROR_SYNTAX,
89             1100 => DB_ERROR_NOT_LOCKED,
90             1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
91             1146 => DB_ERROR_NOSUCHTABLE,
92             1048 => DB_ERROR_CONSTRAINT,
93             1216 => DB_ERROR_CONSTRAINT,
94         );
95     }
96
97     // }}}
98     // {{{ connect()
99
100     /**
101      * Connect to a database and log in as the specified user.
102      *
103      * @param string  $dsn        the data source name (see DB::parseDSN for syntax)
104      * @param boolean $persistent (optional) whether the connection should
105      *                            be persistent
106      * @return mixed DB_OK on success, a DB error on failure
107      * @access public
108      */
109     function connect($dsninfo, $persistent = false)
110     {
111         if (!DB::assertExtension('mysqli')) {
112             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
113         }
114
115         $this->dsn = $dsninfo;
116         if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') {
117             $dbhost = ':' . $dsninfo['socket'];
118         } else {
119             $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
120             if ($dsninfo['port']) {
121                 $dbhost .= ':' . $dsninfo['port'];
122             }
123         }
124
125         $ssl_mode = $this->getOption('ssl') === true ? 'CLIENT_SSL' : NULL;
126
127         @ini_set('track_errors', true);
128
129         if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
130             // Need to verify if arguments are okay
131             $conn = @mysqli_connect($dbhost, $dsninfo['username'],
132                                     $dsninfo['password'], $ssl_mode);
133         } elseif ($dbhost && isset($dsninfo['username'])) {
134             $conn = @mysqli_connect($dbhost, $dsninfo['username'], null,
135                                     $ssl_mode);
136         } elseif ($dbhost) {
137             $conn = @mysqli_connect($dbhost, null, null, $ssl_mode);
138         } else {
139             $conn = false;
140         }
141
142         @ini_restore('track_errors');
143
144         if (!$conn) {
145             if (($err = @mysqli_error()) != '') {
146                 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
147                                          null, $err);
148             } elseif (empty($php_errormsg)) {
149                 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
150             } else {
151                 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
152                                          null, $php_errormsg);
153             }
154         }
155
156         if ($dsninfo['database']) {
157             if (!@mysqli_select_db($dsninfo['database'], $conn)) {
158                 switch(mysqli_errno($conn)) {
159                     case 1049:
160                         return $this->raiseError(DB_ERROR_NOSUCHDB, null, null,
161                                                  null, @mysqli_error($conn));
162                     case 1044:
163                          return $this->raiseError(DB_ERROR_ACCESS_VIOLATION, null, null,
164                                                   null, @mysqli_error($conn));
165                     default:
166                         return $this->raiseError(DB_ERROR, null, null,
167                                                  null, @mysqli_error($conn));
168                 }
169             }
170             // fix to allow calls to different databases in the same script
171             $this->_db = $dsninfo['database'];
172         }
173
174         $this->connection = $conn;
175         return DB_OK;
176     }
177
178     // }}}
179     // {{{ disconnect()
180
181     /**
182      * Log out and disconnect from the database.
183      *
184      * @return boolean true on success, false if not connected
185      * @access public
186      */
187     function disconnect()
188     {
189         $ret = @mysqli_close($this->connection);
190         $this->connection = null;
191         return $ret;
192     }
193
194     // }}}
195     // {{{ simpleQuery()
196
197     /**
198      * Send a query to MySQL and return the results as a MySQL resource
199      * identifier.
200      *
201      * @param  string $query the SQL query
202      * @return mixed  a valid MySQL result for successful SELECT
203      *               queries, DB_OK for other successful queries.
204      *               A DB error is returned on failure.
205      * @access public
206      */
207     function simpleQuery($query)
208     {
209         $ismanip = DB::isManip($query);
210         $this->last_query = $query;
211         $query = $this->modifyQuery($query);
212         if ($this->_db) {
213             if (!@mysqli_select_db($this->_db, $this->connection)) {
214                 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
215             }
216         }
217         if (!$this->autocommit && $ismanip) {
218             if ($this->transaction_opcount == 0) {
219                 $result = @mysqli_query('SET AUTOCOMMIT=0', $this->connection);
220                 $result = @mysqli_query('BEGIN', $this->connection);
221                 if (!$result) {
222                     return $this->mysqlRaiseError();
223                 }
224             }
225             $this->transaction_opcount++;
226         }
227         $result = @mysqli_query($query, $this->connection);
228         if (!$result) {
229             return $this->mysqlRaiseError();
230         }
231         if (is_resource($result)) {
232             $numrows = $this->numrows($result);
233             if (is_object($numrows)) {
234                 return $numrows;
235             }
236             $this->num_rows[(int)$result] = $numrows;
237             return $result;
238         }
239         return DB_OK;
240     }
241
242     // }}}
243     // {{{ nextResult()
244
245     /**
246      * Move the internal mysql result pointer to the next available result.
247      *
248      * This method has not been implemented yet.
249      *
250      * @param  resource $result a valid sql result resource
251      * @return false
252      * @access public
253      */
254     function nextResult($result)
255     {
256         return false;
257     }
258
259     // }}}
260     // {{{ fetchInto()
261
262     /**
263      * Fetch a row and insert the data into an existing array.
264      *
265      * Formating of the array and the data therein are configurable.
266      * See DB_result::fetchInto() for more information.
267      *
268      * @param resource $result query result identifier
269      * @param array    $arr    (reference) array where data from the row
270      *                            should be placed
271      * @param int $fetchmode how the resulting array should be indexed
272      * @param int $rownum    the row number to fetch
273      *
274      * @return mixed DB_OK on success, null when end of result set is
275      *               reached or on failure
276      *
277      * @see DB_result::fetchInto()
278      * @access private
279      */
280     function fetchInto($result, &$arr, $fetchmode, $rownum=null)
281     {
282         if ($rownum !== null) {
283             if (!@mysqli_data_seek($result, $rownum)) {
284                 return null;
285             }
286         }
287         if ($fetchmode & DB_FETCHMODE_ASSOC) {
288             $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC);
289             if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
290                 $arr = array_change_key_case($arr, CASE_LOWER);
291             }
292         } else {
293             $arr = @mysqli_fetch_row($result);
294         }
295         if (!$arr) {
296             $errno = @mysqli_errno($this->connection);
297             if (!$errno) {
298                 return null;
299             }
300             return $this->mysqlRaiseError($errno);
301         }
302         if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
303             /*
304              * Even though this DBMS already trims output, we do this because
305              * a field might have intentional whitespace at the end that
306              * gets removed by DB_PORTABILITY_RTRIM under another driver.
307              */
308             $this->_rtrimArrayValues($arr);
309         }
310         if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
311             $this->_convertNullArrayValuesToEmpty($arr);
312         }
313         return DB_OK;
314     }
315
316     // }}}
317     // {{{ freeResult()
318
319     /**
320      * Free the internal resources associated with $result.
321      *
322      * @param  resource $result MySQL result identifier
323      * @return bool     true on success, false if $result is invalid
324      * @access public
325      */
326     function freeResult($result)
327     {
328         unset($this->num_rows[(int)$result]);
329         return @mysqli_free_result($result);
330     }
331
332     // }}}
333     // {{{ numCols()
334
335     /**
336      * Get the number of columns in a result set.
337      *
338      * @param $result MySQL result identifier
339      *
340      * @access public
341      *
342      * @return int the number of columns per row in $result
343      */
344     function numCols($result)
345     {
346         $cols = @mysqli_num_fields($result);
347
348         if (!$cols) {
349             return $this->mysqlRaiseError();
350         }
351
352         return $cols;
353     }
354
355     // }}}
356     // {{{ numRows()
357
358     /**
359      * Get the number of rows in a result set.
360      *
361      * @param  resource $result MySQL result identifier
362      * @return int      the number of rows in $result
363      * @access public
364      */
365     function numRows($result)
366     {
367         $rows = @mysqli_num_rows($result);
368         if ($rows === null) {
369             return $this->mysqlRaiseError();
370         }
371         return $rows;
372     }
373
374     // }}}
375     // {{{ autoCommit()
376
377     /**
378      * Enable/disable automatic commits.
379      */
380     function autoCommit($onoff = false)
381     {
382         // XXX if $this->transaction_opcount > 0, we should probably
383         // issue a warning here.
384         $this->autocommit = $onoff ? true : false;
385         return DB_OK;
386     }
387
388     // }}}
389     // {{{ commit()
390
391     /**
392      * Commit the current transaction.
393      */
394     function commit()
395     {
396         if ($this->transaction_opcount > 0) {
397             if ($this->_db) {
398                 if (!@mysqli_select_db($this->_db, $this->connection)) {
399                     return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
400                 }
401             }
402             $result = @mysqli_query('COMMIT', $this->connection);
403             $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
404             $this->transaction_opcount = 0;
405             if (!$result) {
406                 return $this->mysqlRaiseError();
407             }
408         }
409         return DB_OK;
410     }
411
412     // }}}
413     // {{{ rollback()
414
415     /**
416      * Roll back (undo) the current transaction.
417      */
418     function rollback()
419     {
420         if ($this->transaction_opcount > 0) {
421             if ($this->_db) {
422                 if (!@mysqli_select_db($this->_db, $this->connection)) {
423                     return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
424                 }
425             }
426             $result = @mysqli_query('ROLLBACK', $this->connection);
427             $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
428             $this->transaction_opcount = 0;
429             if (!$result) {
430                 return $this->mysqlRaiseError();
431             }
432         }
433         return DB_OK;
434     }
435
436     // }}}
437     // {{{ affectedRows()
438
439     /**
440      * Gets the number of rows affected by the data manipulation
441      * query.  For other queries, this function returns 0.
442      *
443      * @return integer number of rows affected by the last query
444      */
445     function affectedRows()
446     {
447         if (DB::isManip($this->last_query)) {
448             return @mysqli_affected_rows($this->connection);
449         } else {
450             return 0;
451         }
452      }
453
454     // }}}
455     // {{{ errorNative()
456
457     /**
458      * Get the native error code of the last error (if any) that
459      * occured on the current connection.
460      *
461      * @return int native MySQL error code
462      * @access public
463      */
464     function errorNative()
465     {
466         return @mysqli_errno($this->connection);
467     }
468
469     // }}}
470     // {{{ nextId()
471
472     /**
473      * Returns the next free id in a sequence
474      *
475      * @param string  $seq_name name of the sequence
476      * @param boolean $ondemand when true, the seqence is automatically
477      *                           created if it does not exist
478      *
479      * @return int the next id number in the sequence.  DB_Error if problem.
480      *
481      * @internal
482      * @see DB_common::nextID()
483      * @access public
484      */
485     function nextId($seq_name, $ondemand = true)
486     {
487         $seqname = $this->getSequenceName($seq_name);
488         do {
489             $repeat = 0;
490             $this->pushErrorHandling(PEAR_ERROR_RETURN);
491             $result = $this->query("UPDATE ${seqname} ".
492                                    'SET id=LAST_INSERT_ID(id+1)');
493             $this->popErrorHandling();
494             if ($result == DB_OK) {
495                 /** COMMON CASE **/
496                 $id = @mysqli_insert_id($this->connection);
497                 if ($id != 0) {
498                     return $id;
499                 }
500                 /** EMPTY SEQ TABLE **/
501                 // Sequence table must be empty for some reason, so fill it and return 1
502                 // Obtain a user-level lock
503                 $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
504                 if (DB::isError($result)) {
505                     return $this->raiseError($result);
506                 }
507                 if ($result == 0) {
508                     // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error
509                     return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
510                 }
511
512                 // add the default value
513                 $result = $this->query("REPLACE INTO ${seqname} VALUES (0)");
514                 if (DB::isError($result)) {
515                     return $this->raiseError($result);
516                 }
517
518                 // Release the lock
519                 $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
520                 if (DB::isError($result)) {
521                     return $this->raiseError($result);
522                 }
523                 // We know what the result will be, so no need to try again
524                 return 1;
525
526             /** ONDEMAND TABLE CREATION **/
527             } elseif ($ondemand && DB::isError($result) &&
528                 $result->getCode() == DB_ERROR_NOSUCHTABLE)
529             {
530                 $result = $this->createSequence($seq_name);
531                 // Since createSequence initializes the ID to be 1,
532                 // we do not need to retrieve the ID again (or we will get 2)
533                 if (DB::isError($result)) {
534                     return $this->raiseError($result);
535                 } else {
536                     // First ID of a newly created sequence is 1
537                     return 1;
538                 }
539
540             /** BACKWARDS COMPAT **/
541             } elseif (DB::isError($result) &&
542                       $result->getCode() == DB_ERROR_ALREADY_EXISTS)
543             {
544                 // see _BCsequence() comment
545                 $result = $this->_BCsequence($seqname);
546                 if (DB::isError($result)) {
547                     return $this->raiseError($result);
548                 }
549                 $repeat = 1;
550             }
551         } while ($repeat);
552
553         return $this->raiseError($result);
554     }
555
556     /**
557      * Creates a new sequence
558      *
559      * @param string $seq_name name of the new sequence
560      *
561      * @return int DB_OK on success.  A DB_Error object is returned if
562      *              problems arise.
563      *
564      * @internal
565      * @see DB_common::createSequence()
566      * @access public
567      */
568     function createSequence($seq_name)
569     {
570         $seqname = $this->getSequenceName($seq_name);
571         $res = $this->query("CREATE TABLE ${seqname} ".
572                             '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
573                             ' PRIMARY KEY(id))');
574         if (DB::isError($res)) {
575             return $res;
576         }
577         // insert yields value 1, nextId call will generate ID 2
578         return $this->query("INSERT INTO ${seqname} VALUES(0)");
579     }
580
581     // }}}
582     // {{{ dropSequence()
583
584     /**
585      * Deletes a sequence
586      *
587      * @param string $seq_name name of the sequence to be deleted
588      *
589      * @return int DB_OK on success.  DB_Error if problems.
590      *
591      * @internal
592      * @see DB_common::dropSequence()
593      * @access public
594      */
595     function dropSequence($seq_name)
596     {
597         return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
598     }
599
600     // }}}
601     // {{{ _BCsequence()
602
603     /**
604      * Backwards compatibility with old sequence emulation implementation
605      * (clean up the dupes).
606      *
607      * @param  string $seqname The sequence name to clean up
608      * @return mixed  DB_Error or true
609      */
610     function _BCsequence($seqname)
611     {
612         // Obtain a user-level lock... this will release any previous
613         // application locks, but unlike LOCK TABLES, it does not abort
614         // the current transaction and is much less frequently used.
615         $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
616         if (DB::isError($result)) {
617             return $result;
618         }
619         if ($result == 0) {
620             // Failed to get the lock, can't do the conversion, bail
621             // with a DB_ERROR_NOT_LOCKED error
622             return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
623         }
624
625         $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
626         if (DB::isError($highest_id)) {
627             return $highest_id;
628         }
629         // This should kill all rows except the highest
630         // We should probably do something if $highest_id isn't
631         // numeric, but I'm at a loss as how to handle that...
632         $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id");
633         if (DB::isError($result)) {
634             return $result;
635         }
636
637         // If another thread has been waiting for this lock,
638         // it will go thru the above procedure, but will have no
639         // real effect
640         $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
641         if (DB::isError($result)) {
642             return $result;
643         }
644         return true;
645     }
646
647     // }}}
648     // {{{ quoteIdentifier()
649
650     /**
651      * Quote a string so it can be safely used as a table or column name
652      *
653      * Quoting style depends on which database driver is being used.
654      *
655      * MySQL can't handle the backtick character (<kbd>`</kbd>) in
656      * table or column names.
657      *
658      * @param string $str identifier name to be quoted
659      *
660      * @return string quoted identifier string
661      *
662      * @since 1.6.0
663      * @access public
664      * @internal
665      */
666     function quoteIdentifier($str)
667     {
668         return '`' . $str . '`';
669     }
670
671     // }}}
672     // {{{ escapeSimple()
673
674     /**
675      * Escape a string according to the current DBMS's standards
676      *
677      * @param string $str the string to be escaped
678      *
679      * @return string the escaped string
680      *
681      * @internal
682      */
683     function escapeSimple($str) {
684         return @mysqli_real_escape_string($str, $this->connection);
685     }
686
687     // }}}
688     // {{{ modifyQuery()
689
690     function modifyQuery($query)
691     {
692         if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
693             // "DELETE FROM table" gives 0 affected rows in MySQL.
694             // This little hack lets you know how many rows were deleted.
695             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
696                 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
697                                       'DELETE FROM \1 WHERE 1=1', $query);
698             }
699         }
700         return $query;
701     }
702
703     // }}}
704     // {{{ modifyLimitQuery()
705
706     function modifyLimitQuery($query, $from, $count)
707     {
708         if (DB::isManip($query)) {
709             return $query . " LIMIT $count";
710         } else {
711             return $query . " LIMIT $from, $count";
712         }
713     }
714
715     // }}}
716     // {{{ mysqlRaiseError()
717
718     /**
719      * Gather information about an error, then use that info to create a
720      * DB error object and finally return that object.
721      *
722      * @param integer $errno PEAR error number (usually a DB constant) if
723      *                          manually raising an error
724      * @return object DB error object
725      * @see DB_common::errorCode()
726      * @see DB_common::raiseError()
727      */
728     function mysqlRaiseError($errno = null)
729     {
730         if ($errno === null) {
731             if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
732                 $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
733                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
734                 $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
735             } else {
736                 // Doing this in case mode changes during runtime.
737                 $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
738                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
739                 $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
740             }
741             $errno = $this->errorCode(mysqli_errno($this->connection));
742         }
743         return $this->raiseError($errno, null, null, null,
744                                  @mysqli_errno($this->connection) . ' ** ' .
745                                  @mysqli_error($this->connection));
746     }
747
748     // }}}
749     // {{{ tableInfo()
750
751     /**
752      * Returns information about a table or a result set.
753      *
754      * WARNING: this method will probably not work because the mysqli_*()
755      * functions it relies upon may not exist.
756      *
757      * @param object|string $result DB_result object from a query or a
758      *                                string containing the name of a table
759      * @param  int   $mode a valid tableInfo mode
760      * @return array an associative array with the information requested
761      *                or an error object if something is wrong
762      * @access public
763      * @internal
764      * @see DB_common::tableInfo()
765      */
766     function tableInfo($result, $mode = null) {
767         if (isset($result->result)) {
768             /*
769              * Probably received a result object.
770              * Extract the result resource identifier.
771              */
772             $id = $result->result;
773             $got_string = false;
774         } elseif (is_string($result)) {
775             /*
776              * Probably received a table name.
777              * Create a result resource identifier.
778              */
779             $id = @mysqli_list_fields($this->dsn['database'],
780                                      $result, $this->connection);
781             $got_string = true;
782         } else {
783             /*
784              * Probably received a result resource identifier.
785              * Copy it.
786              * Depricated.  Here for compatibility only.
787              */
788             $id = $result;
789             $got_string = false;
790         }
791
792         if (!is_resource($id)) {
793             return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
794         }
795
796         if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
797             $case_func = 'strtolower';
798         } else {
799             $case_func = 'strval';
800         }
801
802         $count = @mysqli_num_fields($id);
803
804         // made this IF due to performance (one if is faster than $count if's)
805         if (!$mode) {
806             for ($i=0; $i<$count; $i++) {
807                 $res[$i]['table'] = $case_func(@mysqli_field_table($id, $i));
808                 $res[$i]['name']  = $case_func(@mysqli_field_name($id, $i));
809                 $res[$i]['type']  = @mysqli_field_type($id, $i);
810                 $res[$i]['len']   = @mysqli_field_len($id, $i);
811                 $res[$i]['flags'] = @mysqli_field_flags($id, $i);
812             }
813         } else { // full
814             $res['num_fields']= $count;
815
816             for ($i=0; $i<$count; $i++) {
817                 $res[$i]['table'] = $case_func(@mysqli_field_table($id, $i));
818                 $res[$i]['name']  = $case_func(@mysqli_field_name($id, $i));
819                 $res[$i]['type']  = @mysqli_field_type($id, $i);
820                 $res[$i]['len']   = @mysqli_field_len($id, $i);
821                 $res[$i]['flags'] = @mysqli_field_flags($id, $i);
822
823                 if ($mode & DB_TABLEINFO_ORDER) {
824                     $res['order'][$res[$i]['name']] = $i;
825                 }
826                 if ($mode & DB_TABLEINFO_ORDERTABLE) {
827                     $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
828                 }
829             }
830         }
831
832         // free the result only if we were called on a table
833         if ($got_string) {
834             @mysqli_free_result($id);
835         }
836         return $res;
837     }
838
839     // }}}
840     // {{{ getSpecialQuery()
841
842     /**
843      * Returns the query needed to get some backend info.
844      *
845      * @param  string $type What kind of info you want to retrieve
846      * @return string The SQL query string
847      */
848     function getSpecialQuery($type)
849     {
850         switch ($type) {
851             case 'tables':
852                 return 'SHOW TABLES';
853             case 'views':
854                 return DB_ERROR_NOT_CAPABLE;
855             case 'users':
856                 $sql = 'select distinct User from user';
857                 if ($this->dsn['database'] != 'mysql') {
858                     $dsn = $this->dsn;
859                     $dsn['database'] = 'mysql';
860                     if (DB::isError($db = DB::connect($dsn))) {
861                         return $db;
862                     }
863                     $sql = $db->getCol($sql);
864                     $db->disconnect();
865                     // XXX Fixme the mysql driver should take care of this
866                     if (!@mysqli_select_db($this->dsn['database'], $this->connection)) {
867                         return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
868                     }
869                 }
870                 return $sql;
871             case 'databases':
872                 return 'SHOW DATABASES';
873             default:
874                 return null;
875         }
876     }
877
878    // }}}
879
880 }
881
882 /*
883  * Local variables:
884  * tab-width: 4
885  * c-basic-offset: 4
886  * End:
887  */
888
889 ?>