3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Database independent query interface
10 * LICENSE: This source file is subject to version 3.0 of the PHP license
11 * that is available through the world-wide-web at the following URI:
12 * http://www.php.net/license/3_0.txt. If you did not receive a copy of
13 * the PHP License and are unable to obtain it through the web, please
14 * send a note to license@php.net so we can mail you a copy immediately.
18 * @author Stig Bakken <ssb@php.net>
19 * @author Tomas V.V.Cox <cox@idecnet.com>
20 * @author Daniel Convissor <danielc@php.net>
21 * @copyright 1997-2007 The PHP Group
22 * @license http://www.php.net/license/3_0.txt PHP License 3.0
23 * @version CVS: $Id: DB.php 315557 2011-08-26 14:32:35Z danielc $
24 * @link http://pear.php.net/package/DB
28 * Obtain the PEAR class so it can be extended from
30 require_once 'PEAR.php';
37 * One of PEAR DB's portable error codes.
38 * @see DB_common::errorCode(), DB::errorMessage()
40 * {@internal If you add an error code here, make sure you also add a textual
41 * version of it in DB::errorMessage().}}
45 * The code returned by many methods upon success970
52 define('DB_ERROR', -1);
57 define('DB_ERROR_SYNTAX', -2);
60 * Tried to insert a duplicate value into a primary or unique index
62 define('DB_ERROR_CONSTRAINT', -3);
65 * An identifier in the query refers to a non-existant object
67 define('DB_ERROR_NOT_FOUND', -4);
70 * Tried to create a duplicate object
72 define('DB_ERROR_ALREADY_EXISTS', -5);
75 * The current driver does not support the action you attempted
77 define('DB_ERROR_UNSUPPORTED', -6);
80 * The number of parameters does not match the number of placeholders
82 define('DB_ERROR_MISMATCH', -7);
85 * A literal submitted did not match the data type expected
87 define('DB_ERROR_INVALID', -8);
90 * The current DBMS does not support the action you attempted
92 define('DB_ERROR_NOT_CAPABLE', -9);
95 * A literal submitted was too long so the end of it was removed
97 define('DB_ERROR_TRUNCATED', -10);
100 * A literal number submitted did not match the data type expected
102 define('DB_ERROR_INVALID_NUMBER', -11);
105 * A literal date submitted did not match the data type expected
107 define('DB_ERROR_INVALID_DATE', -12);
110 * Attempt to divide something by zero
112 define('DB_ERROR_DIVZERO', -13);
115 * A database needs to be selected
117 define('DB_ERROR_NODBSELECTED', -14);
120 * Could not create the object requested
122 define('DB_ERROR_CANNOT_CREATE', -15);
125 * Could not drop the database requested because it does not exist
127 define('DB_ERROR_CANNOT_DROP', -17);
130 * An identifier in the query refers to a non-existant table
132 define('DB_ERROR_NOSUCHTABLE', -18);
135 * An identifier in the query refers to a non-existant column
137 define('DB_ERROR_NOSUCHFIELD', -19);
140 * The data submitted to the method was inappropriate
142 define('DB_ERROR_NEED_MORE_DATA', -20);
145 * The attempt to lock the table failed
147 define('DB_ERROR_NOT_LOCKED', -21);
150 * The number of columns doesn't match the number of values
152 define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
155 * The DSN submitted has problems
157 define('DB_ERROR_INVALID_DSN', -23);
160 * Could not connect to the database
162 define('DB_ERROR_CONNECT_FAILED', -24);
165 * The PHP extension needed for this DBMS could not be found
167 define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
170 * The present user has inadequate permissions to perform the task requestd
172 define('DB_ERROR_ACCESS_VIOLATION', -26);
175 * The database requested does not exist
177 define('DB_ERROR_NOSUCHDB', -27);
180 * Tried to insert a null value into a column that doesn't allow nulls
182 define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
187 // {{{ prepared statement-related
191 * Identifiers for the placeholders used in prepared statements.
192 * @see DB_common::prepare()
196 * Indicates a scalar (<kbd>?</kbd>) placeholder was used
198 * Quote and escape the value as necessary.
200 define('DB_PARAM_SCALAR', 1);
203 * Indicates an opaque (<kbd>&</kbd>) placeholder was used
205 * The value presented is a file name. Extract the contents of that file
206 * and place them in this column.
208 define('DB_PARAM_OPAQUE', 2);
211 * Indicates a misc (<kbd>!</kbd>) placeholder was used
213 * The value should not be quoted or escaped.
215 define('DB_PARAM_MISC', 3);
220 // {{{ binary data-related
224 * The different ways of returning binary data from queries.
228 * Sends the fetched data straight through to output
230 define('DB_BINMODE_PASSTHRU', 1);
233 * Lets you return data as usual
235 define('DB_BINMODE_RETURN', 2);
238 * Converts the data to hex format before returning it
240 * For example the string "123" would become "313233".
242 define('DB_BINMODE_CONVERT', 3);
252 * @see DB_common::setFetchMode()
256 * Indicates the current default fetch mode should be used
257 * @see DB_common::$fetchmode
259 define('DB_FETCHMODE_DEFAULT', 0);
262 * Column data indexed by numbers, ordered from 0 and up
264 define('DB_FETCHMODE_ORDERED', 1);
267 * Column data indexed by column names
269 define('DB_FETCHMODE_ASSOC', 2);
272 * Column data as object properties
274 define('DB_FETCHMODE_OBJECT', 3);
277 * For multi-dimensional results, make the column name the first level
278 * of the array and put the row number in the second level of the array
280 * This is flipped from the normal behavior, which puts the row numbers
281 * in the first level of the array and the column names in the second level.
283 define('DB_FETCHMODE_FLIPPED', 4);
287 * Old fetch modes. Left here for compatibility.
289 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
290 define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
291 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
296 // {{{ tableInfo() && autoPrepare()-related
300 * The type of information to return from the tableInfo() method.
302 * Bitwised constants, so they can be combined using <kbd>|</kbd>
303 * and removed using <kbd>^</kbd>.
305 * @see DB_common::tableInfo()
307 * {@internal Since the TABLEINFO constants are bitwised, if more of them are
308 * added in the future, make sure to adjust DB_TABLEINFO_FULL accordingly.}}
310 define('DB_TABLEINFO_ORDER', 1);
311 define('DB_TABLEINFO_ORDERTABLE', 2);
312 define('DB_TABLEINFO_FULL', 3);
317 * The type of query to create with the automatic query building methods.
318 * @see DB_common::autoPrepare(), DB_common::autoExecute()
320 define('DB_AUTOQUERY_INSERT', 1);
321 define('DB_AUTOQUERY_UPDATE', 2);
326 // {{{ portability modes
332 * Bitwised constants, so they can be combined using <kbd>|</kbd>
333 * and removed using <kbd>^</kbd>.
335 * @see DB_common::setOption()
337 * {@internal Since the PORTABILITY constants are bitwised, if more of them are
338 * added in the future, make sure to adjust DB_PORTABILITY_ALL accordingly.}}
342 * Turn off all portability features
344 define('DB_PORTABILITY_NONE', 0);
347 * Convert names of tables and fields to lower case
348 * when using the get*(), fetch*() and tableInfo() methods
350 define('DB_PORTABILITY_LOWERCASE', 1);
353 * Right trim the data output by get*() and fetch*()
355 define('DB_PORTABILITY_RTRIM', 2);
358 * Force reporting the number of rows deleted
360 define('DB_PORTABILITY_DELETE_COUNT', 4);
363 * Enable hack that makes numRows() work in Oracle
365 define('DB_PORTABILITY_NUMROWS', 8);
368 * Makes certain error messages in certain drivers compatible
369 * with those from other DBMS's
371 * + mysql, mysqli: change unique/primary key constraints
372 * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
374 * + odbc(access): MS's ODBC driver reports 'no such field' as code
375 * 07001, which means 'too few parameters.' When this option is on
376 * that code gets mapped to DB_ERROR_NOSUCHFIELD.
378 define('DB_PORTABILITY_ERRORS', 16);
381 * Convert null values to empty strings in data output by
382 * get*() and fetch*()
384 define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
387 * Convert boolean values to true/false (normally with postgres)
389 define('DB_PORTABILITY_BOOLEAN', 64);
392 * Turn on all portability features
394 define('DB_PORTABILITY_ALL', 127);
404 * Database independent query interface
406 * The main "DB" class is simply a container class with some static
407 * methods for creating DB objects as well as some utility functions
408 * common to all parts of DB.
410 * The object model of DB is as follows (indentation means inheritance):
412 * DB The main DB class. This is simply a utility class
413 * with some "static" methods for creating DB objects as
414 * well as common utility functions for other DB classes.
416 * DB_common The base for each DB implementation. Provides default
417 * | implementations (in OO lingo virtual methods) for
418 * | the actual DB implementations as well as a bunch of
419 * | query utility functions.
421 * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
422 * When calling DB::factory or DB::connect for MySQL
423 * connections, the object returned is an instance of this
429 * @author Stig Bakken <ssb@php.net>
430 * @author Tomas V.V.Cox <cox@idecnet.com>
431 * @author Daniel Convissor <danielc@php.net>
432 * @copyright 1997-2007 The PHP Group
433 * @license http://www.php.net/license/3_0.txt PHP License 3.0
434 * @version Release: 1.7.14
435 * @link http://pear.php.net/package/DB
442 * Create a new DB object for the specified database type but don't
443 * connect to the database
445 * @param string $type the database type (eg "mysql")
446 * @param array $options an associative array of option names and values
448 * @return object a new DB object. A DB_Error object on failure.
450 * @see DB_common::setOption()
452 function &factory($type, $options = false)
454 if (!is_array($options)) {
455 $options = array('persistent' => $options);
458 if (isset($options['debug']) && $options['debug'] >= 2) {
459 // expose php errors with sufficient debug level
460 include_once "DB/{$type}.php";
462 include_once "DB/{$type}.php";
465 $classname = "DB_{$type}";
467 if (!class_exists($classname)) {
468 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
469 "Unable to include the DB/{$type}.php"
470 . " file for '$dsn'",
475 @$obj = new $classname;
477 foreach ($options as $option => $value) {
478 $test = $obj->setOption($option, $value);
479 if (DB::isError($test)) {
491 * Create a new DB object including a connection to the specified database
495 * require_once 'DB.php';
497 * $dsn = 'pgsql://user:password@host/database';
500 * 'portability' => DB_PORTABILITY_ALL,
503 * $db =& DB::connect($dsn, $options);
504 * if (PEAR::isError($db)) {
505 * die($db->getMessage());
509 * @param mixed $dsn the string "data source name" or array in the
510 * format returned by DB::parseDSN()
511 * @param array $options an associative array of option names and values
513 * @return object a new DB object. A DB_Error object on failure.
515 * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
516 * DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
517 * DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
518 * DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
519 * DB_sybase::connect()
521 * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
523 static function connect($dsn, $options = array())
525 $dsninfo = DB::parseDSN($dsn);
526 $type = $dsninfo['phptype'];
528 if (!is_array($options)) {
530 * For backwards compatibility. $options used to be boolean,
531 * indicating whether the connection should be persistent.
533 $options = array('persistent' => $options);
536 if (isset($options['debug']) && $options['debug'] >= 2) {
537 // expose php errors with sufficient debug level
538 include_once "DB/{$type}.php";
540 @include_once "DB/{$type}.php";
543 $classname = "DB_{$type}";
544 if (!class_exists($classname)) {
545 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
546 "Unable to include the DB/{$type}.php"
547 . " file for '$dsn'",
552 $obj = new $classname;
554 foreach ($options as $option => $value) {
555 $test = $obj->setOption($option, $value);
556 if (DB::isError($test)) {
561 $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
562 if (DB::isError($err)) {
563 if (is_array($dsn)) {
564 $err->addUserInfo(DB::getDSNString($dsn, true));
566 $err->addUserInfo($dsn);
578 * Return the DB API version
580 * @return string the DB API version number
582 function apiVersion()
591 * Determines if a variable is a DB_Error object
593 * @param mixed $value the variable to check
595 * @return bool whether $value is DB_Error object
597 static function isError($value)
599 return is_object($value) && is_a($value, 'DB_Error');
603 // {{{ isConnection()
606 * Determines if a value is a DB_<driver> object
608 * @param mixed $value the value to test
610 * @return bool whether $value is a DB_<driver> object
612 function isConnection($value)
614 return (is_object($value) &&
615 is_subclass_of($value, 'db_common') &&
616 method_exists($value, 'simpleQuery'));
623 * Tell whether a query is a data manipulation or data definition query
625 * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
626 * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
629 * @param string $query the query
631 * @return boolean whether $query is a data manipulation query
633 static function isManip($query)
635 $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
637 . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
638 . 'ALTER|GRANT|REVOKE|'
640 if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
647 // {{{ errorMessage()
650 * Return a textual error message for a DB error code
652 * @param integer $value the DB error code
654 * @return string the error message or false if the error code was
658 static function errorMessage($value)
660 static $errorMessages;
661 if (!isset($errorMessages)) {
662 $errorMessages = array(
663 DB_ERROR => 'unknown error',
664 DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
665 DB_ERROR_ALREADY_EXISTS => 'already exists',
666 DB_ERROR_CANNOT_CREATE => 'can not create',
667 DB_ERROR_CANNOT_DROP => 'can not drop',
668 DB_ERROR_CONNECT_FAILED => 'connect failed',
669 DB_ERROR_CONSTRAINT => 'constraint violation',
670 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
671 DB_ERROR_DIVZERO => 'division by zero',
672 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
673 DB_ERROR_INVALID => 'invalid',
674 DB_ERROR_INVALID_DATE => 'invalid date or time',
675 DB_ERROR_INVALID_DSN => 'invalid DSN',
676 DB_ERROR_INVALID_NUMBER => 'invalid number',
677 DB_ERROR_MISMATCH => 'mismatch',
678 DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
679 DB_ERROR_NODBSELECTED => 'no database selected',
680 DB_ERROR_NOSUCHDB => 'no such database',
681 DB_ERROR_NOSUCHFIELD => 'no such field',
682 DB_ERROR_NOSUCHTABLE => 'no such table',
683 DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
684 DB_ERROR_NOT_FOUND => 'not found',
685 DB_ERROR_NOT_LOCKED => 'not locked',
686 DB_ERROR_SYNTAX => 'syntax error',
687 DB_ERROR_UNSUPPORTED => 'not supported',
688 DB_ERROR_TRUNCATED => 'truncated',
689 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
694 if (DB::isError($value)) {
695 $value = $value->getCode();
698 return isset($errorMessages[$value]) ? $errorMessages[$value]
699 : $errorMessages[DB_ERROR];
706 * Parse a data source name
708 * Additional keys can be added by appending a URI query string to the
711 * The format of the supplied DSN is in its fullest form:
713 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
716 * Most variations are allowed:
718 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
719 * phptype://username:password@hostspec/database_name
720 * phptype://username:password@hostspec
721 * phptype://username@hostspec
722 * phptype://hostspec/database
728 * @param string $dsn Data Source Name to be parsed
730 * @return array an associative array with the following keys:
731 * + phptype: Database backend used in PHP (mysql, odbc etc.)
732 * + dbsyntax: Database used with regards to SQL syntax etc.
733 * + protocol: Communication protocol to use (tcp, unix etc.)
734 * + hostspec: Host specification (hostname[:port])
735 * + database: Database to use on the DBMS server
736 * + username: User name for login
737 * + password: Password for login
739 static function parseDSN($dsn)
753 if (is_array($dsn)) {
754 $dsn = array_merge($parsed, $dsn);
755 if (!$dsn['dbsyntax']) {
756 $dsn['dbsyntax'] = $dsn['phptype'];
761 // Find phptype and dbsyntax
762 if (($pos = strpos($dsn, '://')) !== false) {
763 $str = substr($dsn, 0, $pos);
764 $dsn = substr($dsn, $pos + 3);
770 // Get phptype and dbsyntax
771 // $str => phptype(dbsyntax)
772 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
773 $parsed['phptype'] = $arr[1];
774 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
776 $parsed['phptype'] = $str;
777 $parsed['dbsyntax'] = $str;
786 // Get (if found): username and password
787 // $dsn => username:password@protocol+hostspec/database
788 if (($at = strrpos($dsn,'@')) !== false) {
789 $str = substr($dsn, 0, $at);
790 $dsn = substr($dsn, $at + 1);
791 if (($pos = strpos($str, ':')) !== false) {
792 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
793 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
795 $parsed['username'] = rawurldecode($str);
799 // Find protocol and hostspec
801 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
802 // $dsn => proto(proto_opts)/database
804 $proto_opts = $match[2] ? $match[2] : false;
808 // $dsn => protocol+hostspec/database (old format)
809 if (strpos($dsn, '+') !== false) {
810 list($proto, $dsn) = explode('+', $dsn, 2);
812 if (strpos($dsn, '/') !== false) {
813 list($proto_opts, $dsn) = explode('/', $dsn, 2);
820 // process the different protocol options
821 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
822 $proto_opts = rawurldecode($proto_opts);
823 if (strpos($proto_opts, ':') !== false) {
824 list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
826 if ($parsed['protocol'] == 'tcp') {
827 $parsed['hostspec'] = $proto_opts;
828 } elseif ($parsed['protocol'] == 'unix') {
829 $parsed['socket'] = $proto_opts;
835 if (($pos = strpos($dsn, '?')) === false) {
837 $parsed['database'] = rawurldecode($dsn);
839 // /database?param1=value1¶m2=value2
840 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
841 $dsn = substr($dsn, $pos + 1);
842 if (strpos($dsn, '&') !== false) {
843 $opts = explode('&', $dsn);
844 } else { // database?param1=value1
847 foreach ($opts as $opt) {
848 list($key, $value) = explode('=', $opt);
849 if (!isset($parsed[$key])) {
850 // don't allow params overwrite
851 $parsed[$key] = rawurldecode($value);
861 // {{{ getDSNString()
864 * Returns the given DSN in a string format suitable for output.
866 * @param array|string the DSN to parse and format
867 * @param boolean true to hide the password, false to include it
870 function getDSNString($dsn, $hidePassword) {
871 /* Calling parseDSN will ensure that we have all the array elements
872 * defined, and means that we deal with strings and array in the same
874 $dsnArray = DB::parseDSN($dsn);
877 $dsnArray['password'] = 'PASSWORD';
880 /* Protocol is special-cased, as using the default "tcp" along with an
881 * Oracle TNS connection string fails. */
882 if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
883 $dsnArray['protocol'] = false;
886 // Now we just have to construct the actual string. This is ugly.
887 $dsnString = $dsnArray['phptype'];
888 if ($dsnArray['dbsyntax']) {
889 $dsnString .= '('.$dsnArray['dbsyntax'].')';
892 .$dsnArray['username']
894 .$dsnArray['password']
896 .$dsnArray['protocol'];
897 if ($dsnArray['socket']) {
898 $dsnString .= '('.$dsnArray['socket'].')';
900 if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
903 $dsnString .= $dsnArray['hostspec'];
904 if ($dsnArray['port']) {
905 $dsnString .= ':'.$dsnArray['port'];
907 $dsnString .= '/'.$dsnArray['database'];
909 /* Option handling. Unfortunately, parseDSN simply places options into
910 * the top-level array, so we'll first get rid of the fields defined by
911 * DB and see what's left. */
912 unset($dsnArray['phptype'],
913 $dsnArray['dbsyntax'],
914 $dsnArray['username'],
915 $dsnArray['password'],
916 $dsnArray['protocol'],
918 $dsnArray['hostspec'],
920 $dsnArray['database']
922 if (count($dsnArray) > 0) {
925 foreach ($dsnArray as $key => $value) {
929 $dsnString .= $key.'='.$value;
940 // {{{ class DB_Error
943 * DB_Error implements a class for reporting portable database error
948 * @author Stig Bakken <ssb@php.net>
949 * @copyright 1997-2007 The PHP Group
950 * @license http://www.php.net/license/3_0.txt PHP License 3.0
951 * @version Release: 1.7.14
952 * @link http://pear.php.net/package/DB
954 class DB_Error extends PEAR_Error
959 * DB_Error constructor
961 * @param mixed $code DB error code, or string with error message
962 * @param int $mode what "error mode" to operate in
963 * @param int $level what error level to use for $mode &
965 * @param mixed $debuginfo additional debug info, such as the last query
969 function __construct($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
970 $level = E_USER_NOTICE, $debuginfo = null)
973 parent::__construct('DB Error: ' . DB::errorMessage($code), $code,
974 $mode, $level, $debuginfo);
976 parent::__construct("DB Error: $code", DB_ERROR,
977 $mode, $level, $debuginfo);
985 // {{{ class DB_result
988 * This class implements a wrapper for a DB result set
990 * A new instance of this class will be returned by the DB implementation
991 * after processing a query that returns data.
995 * @author Stig Bakken <ssb@php.net>
996 * @copyright 1997-2007 The PHP Group
997 * @license http://www.php.net/license/3_0.txt PHP License 3.0
998 * @version Release: 1.7.14
999 * @link http://pear.php.net/package/DB
1006 * Should results be freed automatically when there are no more rows?
1008 * @see DB_common::$options
1013 * A reference to the DB_<driver> object
1019 * The current default fetch mode
1021 * @see DB_common::$fetchmode
1026 * The name of the class into which results should be fetched when
1027 * DB_FETCHMODE_OBJECT is in effect
1030 * @see DB_common::$fetchmode_object_class
1032 var $fetchmode_object_class;
1035 * The number of rows to fetch from a limit query
1038 var $limit_count = null;
1041 * The row to start fetching from in limit queries
1044 var $limit_from = null;
1047 * The execute parameters that created this result
1049 * @since Property available since Release 1.7.0
1054 * The query string that created this result
1056 * Copied here incase it changes in $dbh, which is referenced
1059 * @since Property available since Release 1.7.0
1064 * The query result resource id created by PHP
1070 * The present row being dealt with
1073 var $row_counter = null;
1076 * The prepared statement resource id created by PHP in $dbh
1078 * This resource is only available when the result set was created using
1079 * a driver's native execute() method, not PEAR DB's emulated one.
1081 * Copied here incase it changes in $dbh, which is referenced
1083 * {@internal Mainly here because the InterBase/Firebird API is only
1084 * able to retrieve data from result sets if the statemnt handle is
1088 * @since Property available since Release 1.7.0
1097 * This constructor sets the object's properties
1099 * @param object &$dbh the DB object reference
1100 * @param resource $result the result resource id
1101 * @param array $options an associative array with result options
1105 function __construct(&$dbh, $result, $options = array())
1107 $this->autofree = $dbh->options['autofree'];
1109 $this->fetchmode = $dbh->fetchmode;
1110 $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1111 $this->parameters = $dbh->last_parameters;
1112 $this->query = $dbh->last_query;
1113 $this->result = $result;
1114 $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1115 foreach ($options as $key => $value) {
1116 $this->setOption($key, $value);
1121 * Set options for the DB_result object
1123 * @param string $key the option to set
1124 * @param mixed $value the value to set the option to
1128 function setOption($key, $value = null)
1132 $this->limit_from = $value;
1135 $this->limit_count = $value;
1143 * Fetch a row of data and return it by reference into an array
1145 * The type of array returned can be controlled either by setting this
1146 * method's <var>$fetchmode</var> parameter or by changing the default
1147 * fetch mode setFetchMode() before calling this method.
1149 * There are two options for standardizing the information returned
1150 * from databases, ensuring their values are consistent when changing
1151 * DBMS's. These portability options can be turned on when creating a
1152 * new DB object or by using setOption().
1154 * + <var>DB_PORTABILITY_LOWERCASE</var>
1155 * convert names of fields to lower case
1157 * + <var>DB_PORTABILITY_RTRIM</var>
1158 * right trim the data
1160 * @param int $fetchmode the constant indicating how to format the data
1161 * @param int $rownum the row number to fetch (index starts at 0)
1163 * @return mixed an array or object containing the row's data,
1164 * NULL when the end of the result set is reached
1165 * or a DB_Error object on failure.
1167 * @see DB_common::setOption(), DB_common::setFetchMode()
1169 function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1171 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1172 $fetchmode = $this->fetchmode;
1174 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1175 $fetchmode = DB_FETCHMODE_ASSOC;
1176 $object_class = $this->fetchmode_object_class;
1178 if (is_null($rownum) && $this->limit_from !== null) {
1179 if ($this->row_counter === null) {
1180 $this->row_counter = $this->limit_from;
1182 if ($this->dbh->features['limit'] === false) {
1184 while ($i++ < $this->limit_from) {
1185 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1189 if ($this->row_counter >= ($this->limit_from + $this->limit_count))
1191 if ($this->autofree) {
1197 if ($this->dbh->features['limit'] === 'emulate') {
1198 $rownum = $this->row_counter;
1200 $this->row_counter++;
1202 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1203 if ($res === DB_OK) {
1204 if (isset($object_class)) {
1205 // The default mode is specified in the
1206 // DB_common::fetchmode_object_class property
1207 if ($object_class == 'stdClass') {
1208 $arr = (object) $arr;
1210 $arr = new $object_class($arr);
1215 if ($res == null && $this->autofree) {
1225 * Fetch a row of data into an array which is passed by reference
1227 * The type of array returned can be controlled either by setting this
1228 * method's <var>$fetchmode</var> parameter or by changing the default
1229 * fetch mode setFetchMode() before calling this method.
1231 * There are two options for standardizing the information returned
1232 * from databases, ensuring their values are consistent when changing
1233 * DBMS's. These portability options can be turned on when creating a
1234 * new DB object or by using setOption().
1236 * + <var>DB_PORTABILITY_LOWERCASE</var>
1237 * convert names of fields to lower case
1239 * + <var>DB_PORTABILITY_RTRIM</var>
1240 * right trim the data
1242 * @param array &$arr the variable where the data should be placed
1243 * @param int $fetchmode the constant indicating how to format the data
1244 * @param int $rownum the row number to fetch (index starts at 0)
1246 * @return mixed DB_OK if a row is processed, NULL when the end of the
1247 * result set is reached or a DB_Error object on failure
1249 * @see DB_common::setOption(), DB_common::setFetchMode()
1251 function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1253 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1254 $fetchmode = $this->fetchmode;
1256 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1257 $fetchmode = DB_FETCHMODE_ASSOC;
1258 $object_class = $this->fetchmode_object_class;
1260 if (is_null($rownum) && $this->limit_from !== null) {
1261 if ($this->row_counter === null) {
1262 $this->row_counter = $this->limit_from;
1264 if ($this->dbh->features['limit'] === false) {
1266 while ($i++ < $this->limit_from) {
1267 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1271 if ($this->row_counter >= (
1272 $this->limit_from + $this->limit_count))
1274 if ($this->autofree) {
1279 if ($this->dbh->features['limit'] === 'emulate') {
1280 $rownum = $this->row_counter;
1283 $this->row_counter++;
1285 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1286 if ($res === DB_OK) {
1287 if (isset($object_class)) {
1288 // default mode specified in the
1289 // DB_common::fetchmode_object_class property
1290 if ($object_class == 'stdClass') {
1291 $arr = (object) $arr;
1293 $arr = new $object_class($arr);
1298 if ($res == null && $this->autofree) {
1308 * Get the the number of columns in a result set
1310 * @return int the number of columns. A DB_Error object on failure.
1314 return $this->dbh->numCols($this->result);
1321 * Get the number of rows in a result set
1323 * @return int the number of rows. A DB_Error object on failure.
1327 if ($this->dbh->features['numrows'] === 'emulate'
1328 && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
1330 if ($this->dbh->features['prepare']) {
1331 $res = $this->dbh->query($this->query, $this->parameters);
1333 $res = $this->dbh->query($this->query);
1335 if (DB::isError($res)) {
1339 while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1344 $count = $this->dbh->numRows($this->result);
1347 /* fbsql is checked for here because limit queries are implemented
1348 * using a TOP() function, which results in fbsql_num_rows still
1349 * returning the total number of rows that would have been returned,
1350 * rather than the real number. As a result, we'll just do the limit
1351 * calculations for fbsql in the same way as a database with emulated
1352 * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1353 * because that only gets the result resource, rather than the full
1354 * DB_Result object. */
1355 if (($this->dbh->features['limit'] === 'emulate'
1356 && $this->limit_from !== null)
1357 || $this->dbh->phptype == 'fbsql') {
1358 $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1359 if ($count < $this->limit_from) {
1361 } elseif ($count < ($this->limit_from + $limit_count)) {
1362 $count -= $this->limit_from;
1364 $count = $limit_count;
1375 * Get the next result if a batch of queries was executed
1377 * @return bool true if a new result is available or false if not
1379 function nextResult()
1381 return $this->dbh->nextResult($this->result);
1388 * Frees the resources allocated for this result set
1390 * @return bool true on success. A DB_Error object on failure.
1394 $err = $this->dbh->freeResult($this->result);
1395 if (DB::isError($err)) {
1398 $this->result = false;
1399 $this->statement = false;
1407 * @see DB_common::tableInfo()
1408 * @deprecated Method deprecated some time before Release 1.2
1410 function tableInfo($mode = null)
1412 if (is_string($mode)) {
1413 return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1415 return $this->dbh->tableInfo($this, $mode);
1422 * Determine the query string that created this result
1424 * @return string the query string
1426 * @since Method available since Release 1.7.0
1430 return $this->query;
1434 // {{{ getRowCounter()
1437 * Tells which row number is currently being processed
1439 * @return integer the current row being looked at. Starts at 1.
1441 function getRowCounter()
1443 return $this->row_counter;
1453 * PEAR DB Row Object
1455 * The object contains a row of data from a result set. Each column's data
1456 * is placed in a property named for the column.
1458 * @category Database
1460 * @author Stig Bakken <ssb@php.net>
1461 * @copyright 1997-2007 The PHP Group
1462 * @license http://www.php.net/license/3_0.txt PHP License 3.0
1463 * @version Release: 1.7.14
1464 * @link http://pear.php.net/package/DB
1465 * @see DB_common::setFetchMode()
1472 * The constructor places a row's data into properties of this object
1474 * @param array the array containing the row's data
1478 function __construct(&$arr)
1480 foreach ($arr as $key => $value) {
1481 $this->$key = &$arr[$key];