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
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 success
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 * Turn on all portability features
389 define('DB_PORTABILITY_ALL', 63);
399 * Database independent query interface
401 * The main "DB" class is simply a container class with some static
402 * methods for creating DB objects as well as some utility functions
403 * common to all parts of DB.
405 * The object model of DB is as follows (indentation means inheritance):
407 * DB The main DB class. This is simply a utility class
408 * with some "static" methods for creating DB objects as
409 * well as common utility functions for other DB classes.
411 * DB_common The base for each DB implementation. Provides default
412 * | implementations (in OO lingo virtual methods) for
413 * | the actual DB implementations as well as a bunch of
414 * | query utility functions.
416 * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
417 * When calling DB::factory or DB::connect for MySQL
418 * connections, the object returned is an instance of this
424 * @author Stig Bakken <ssb@php.net>
425 * @author Tomas V.V.Cox <cox@idecnet.com>
426 * @author Daniel Convissor <danielc@php.net>
427 * @copyright 1997-2007 The PHP Group
428 * @license http://www.php.net/license/3_0.txt PHP License 3.0
429 * @version Release: 1.8.2
430 * @link http://pear.php.net/package/DB
437 * Create a new DB object for the specified database type but don't
438 * connect to the database
440 * @param string $type the database type (eg "mysql")
441 * @param array $options an associative array of option names and values
443 * @return object a new DB object. A DB_Error object on failure.
445 * @see DB_common::setOption()
447 public static function factory($type, $options = false)
449 if (!is_array($options)) {
450 $options = array('persistent' => $options);
453 if (isset($options['debug']) && $options['debug'] >= 2) {
454 // expose php errors with sufficient debug level
455 include_once "DB/{$type}.php";
457 @include_once "DB/{$type}.php";
460 $classname = "DB_${type}";
462 if (!class_exists($classname)) {
463 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
464 "Unable to include the DB/{$type}.php"
465 . " file for '$dsn'",
470 @$obj = new $classname;
472 foreach ($options as $option => $value) {
473 $test = $obj->setOption($option, $value);
474 if (DB::isError($test)) {
486 * Create a new DB object including a connection to the specified database
490 * require_once 'DB.php';
492 * $dsn = 'pgsql://user:password@host/database';
495 * 'portability' => DB_PORTABILITY_ALL,
498 * $db = DB::connect($dsn, $options);
499 * if (PEAR::isError($db)) {
500 * die($db->getMessage());
504 * @param mixed $dsn the string "data source name" or array in the
505 * format returned by DB::parseDSN()
506 * @param array $options an associative array of option names and values
508 * @return object a new DB object. A DB_Error object on failure.
510 * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
511 * DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
512 * DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
513 * DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
514 * DB_sybase::connect()
516 * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
518 public static function connect($dsn, $options = array())
520 $dsninfo = DB::parseDSN($dsn);
521 $type = $dsninfo['phptype'];
523 if (!is_array($options)) {
525 * For backwards compatibility. $options used to be boolean,
526 * indicating whether the connection should be persistent.
528 $options = array('persistent' => $options);
531 if (isset($options['debug']) && $options['debug'] >= 2) {
532 // expose php errors with sufficient debug level
533 include_once "DB/${type}.php";
535 @include_once "DB/${type}.php";
538 $classname = "DB_${type}";
539 if (!class_exists($classname)) {
540 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
541 "Unable to include the DB/{$type}.php"
543 . DB::getDSNString($dsn, true) . "'",
548 @$obj = new $classname;
550 foreach ($options as $option => $value) {
551 $test = $obj->setOption($option, $value);
552 if (DB::isError($test)) {
557 $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
558 if (DB::isError($err)) {
559 if (is_array($dsn)) {
560 $err->addUserInfo(DB::getDSNString($dsn, true));
562 $err->addUserInfo($dsn);
574 * Return the DB API version
576 * @return string the DB API version number
578 function apiVersion()
587 * Determines if a variable is a DB_Error object
589 * @param mixed $value the variable to check
591 * @return bool whether $value is DB_Error object
593 public static function isError($value)
595 return is_object($value) && is_a($value, 'DB_Error');
599 // {{{ isConnection()
602 * Determines if a value is a DB_<driver> object
604 * @param mixed $value the value to test
606 * @return bool whether $value is a DB_<driver> object
608 public static function isConnection($value)
610 return (is_object($value) &&
611 is_subclass_of($value, 'db_common') &&
612 method_exists($value, 'simpleQuery'));
619 * Tell whether a query is a data manipulation or data definition query
621 * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
622 * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
625 * @param string $query the query
627 * @return boolean whether $query is a data manipulation query
629 public static function isManip($query)
631 $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
633 . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
634 . 'ALTER|GRANT|REVOKE|'
636 if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
643 // {{{ errorMessage()
646 * Return a textual error message for a DB error code
648 * @param integer $value the DB error code
650 * @return string the error message or false if the error code was
653 public static function errorMessage($value)
655 static $errorMessages;
656 if (!isset($errorMessages)) {
657 $errorMessages = array(
658 DB_ERROR => 'unknown error',
659 DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
660 DB_ERROR_ALREADY_EXISTS => 'already exists',
661 DB_ERROR_CANNOT_CREATE => 'can not create',
662 DB_ERROR_CANNOT_DROP => 'can not drop',
663 DB_ERROR_CONNECT_FAILED => 'connect failed',
664 DB_ERROR_CONSTRAINT => 'constraint violation',
665 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
666 DB_ERROR_DIVZERO => 'division by zero',
667 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
668 DB_ERROR_INVALID => 'invalid',
669 DB_ERROR_INVALID_DATE => 'invalid date or time',
670 DB_ERROR_INVALID_DSN => 'invalid DSN',
671 DB_ERROR_INVALID_NUMBER => 'invalid number',
672 DB_ERROR_MISMATCH => 'mismatch',
673 DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
674 DB_ERROR_NODBSELECTED => 'no database selected',
675 DB_ERROR_NOSUCHDB => 'no such database',
676 DB_ERROR_NOSUCHFIELD => 'no such field',
677 DB_ERROR_NOSUCHTABLE => 'no such table',
678 DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
679 DB_ERROR_NOT_FOUND => 'not found',
680 DB_ERROR_NOT_LOCKED => 'not locked',
681 DB_ERROR_SYNTAX => 'syntax error',
682 DB_ERROR_UNSUPPORTED => 'not supported',
683 DB_ERROR_TRUNCATED => 'truncated',
684 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
689 if (DB::isError($value)) {
690 $value = $value->getCode();
693 return isset($errorMessages[$value]) ? $errorMessages[$value]
694 : $errorMessages[DB_ERROR];
701 * Parse a data source name
703 * Additional keys can be added by appending a URI query string to the
706 * The format of the supplied DSN is in its fullest form:
708 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
711 * Most variations are allowed:
713 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
714 * phptype://username:password@hostspec/database_name
715 * phptype://username:password@hostspec
716 * phptype://username@hostspec
717 * phptype://hostspec/database
723 * @param string $dsn Data Source Name to be parsed
725 * @return array an associative array with the following keys:
726 * + phptype: Database backend used in PHP (mysql, odbc etc.)
727 * + dbsyntax: Database used with regards to SQL syntax etc.
728 * + protocol: Communication protocol to use (tcp, unix etc.)
729 * + hostspec: Host specification (hostname[:port])
730 * + database: Database to use on the DBMS server
731 * + username: User name for login
732 * + password: Password for login
734 public static function parseDSN($dsn)
748 if (is_array($dsn)) {
749 $dsn = array_merge($parsed, $dsn);
750 if (!$dsn['dbsyntax']) {
751 $dsn['dbsyntax'] = $dsn['phptype'];
756 // Find phptype and dbsyntax
757 if (($pos = strpos($dsn, '://')) !== false) {
758 $str = substr($dsn, 0, $pos);
759 $dsn = substr($dsn, $pos + 3);
765 // Get phptype and dbsyntax
766 // $str => phptype(dbsyntax)
767 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
768 $parsed['phptype'] = $arr[1];
769 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
771 $parsed['phptype'] = $str;
772 $parsed['dbsyntax'] = $str;
779 // Get (if found): username and password
780 // $dsn => username:password@protocol+hostspec/database
781 if (($at = strrpos($dsn,'@')) !== false) {
782 $str = substr($dsn, 0, $at);
783 $dsn = substr($dsn, $at + 1);
784 if (($pos = strpos($str, ':')) !== false) {
785 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
786 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
788 $parsed['username'] = rawurldecode($str);
792 // Find protocol and hostspec
794 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
795 // $dsn => proto(proto_opts)/database
797 $proto_opts = $match[2] ? $match[2] : false;
801 // $dsn => protocol+hostspec/database (old format)
802 if (strpos($dsn, '+') !== false) {
803 list($proto, $dsn) = explode('+', $dsn, 2);
805 if (strpos($dsn, '/') !== false) {
806 list($proto_opts, $dsn) = explode('/', $dsn, 2);
813 // process the different protocol options
814 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
815 $proto_opts = rawurldecode($proto_opts);
816 if (strpos($proto_opts, ':') !== false) {
817 list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
819 if ($parsed['protocol'] == 'tcp') {
820 $parsed['hostspec'] = $proto_opts;
821 } elseif ($parsed['protocol'] == 'unix') {
822 $parsed['socket'] = $proto_opts;
828 if (($pos = strpos($dsn, '?')) === false) {
830 $parsed['database'] = rawurldecode($dsn);
832 // /database?param1=value1¶m2=value2
833 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
834 $dsn = substr($dsn, $pos + 1);
835 if (strpos($dsn, '&') !== false) {
836 $opts = explode('&', $dsn);
837 } else { // database?param1=value1
840 foreach ($opts as $opt) {
841 list($key, $value) = explode('=', $opt);
842 if (!isset($parsed[$key])) {
843 // don't allow params overwrite
844 $parsed[$key] = rawurldecode($value);
854 // {{{ getDSNString()
857 * Returns the given DSN in a string format suitable for output.
859 * @param array|string the DSN to parse and format
860 * @param boolean true to hide the password, false to include it
863 public static function getDSNString($dsn, $hidePassword) {
864 /* Calling parseDSN will ensure that we have all the array elements
865 * defined, and means that we deal with strings and array in the same
867 $dsnArray = DB::parseDSN($dsn);
870 $dsnArray['password'] = 'PASSWORD';
873 /* Protocol is special-cased, as using the default "tcp" along with an
874 * Oracle TNS connection string fails. */
875 if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
876 $dsnArray['protocol'] = false;
879 // Now we just have to construct the actual string. This is ugly.
880 $dsnString = $dsnArray['phptype'];
881 if ($dsnArray['dbsyntax']) {
882 $dsnString .= '('.$dsnArray['dbsyntax'].')';
885 .$dsnArray['username']
887 .$dsnArray['password']
889 .$dsnArray['protocol'];
890 if ($dsnArray['socket']) {
891 $dsnString .= '('.$dsnArray['socket'].')';
893 if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
896 $dsnString .= $dsnArray['hostspec'];
897 if ($dsnArray['port']) {
898 $dsnString .= ':'.$dsnArray['port'];
900 $dsnString .= '/'.$dsnArray['database'];
902 /* Option handling. Unfortunately, parseDSN simply places options into
903 * the top-level array, so we'll first get rid of the fields defined by
904 * DB and see what's left. */
905 unset($dsnArray['phptype'],
906 $dsnArray['dbsyntax'],
907 $dsnArray['username'],
908 $dsnArray['password'],
909 $dsnArray['protocol'],
911 $dsnArray['hostspec'],
913 $dsnArray['database']
915 if (count($dsnArray) > 0) {
918 foreach ($dsnArray as $key => $value) {
922 $dsnString .= $key.'='.$value;
933 // {{{ class DB_Error
936 * DB_Error implements a class for reporting portable database error
941 * @author Stig Bakken <ssb@php.net>
942 * @copyright 1997-2007 The PHP Group
943 * @license http://www.php.net/license/3_0.txt PHP License 3.0
944 * @version Release: 1.8.2
945 * @link http://pear.php.net/package/DB
947 class DB_Error extends PEAR_Error
952 * DB_Error constructor
954 * @param mixed $code DB error code, or string with error message
955 * @param int $mode what "error mode" to operate in
956 * @param int $level what error level to use for $mode &
958 * @param mixed $debuginfo additional debug info, such as the last query
962 function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
963 $level = E_USER_NOTICE, $debuginfo = null)
966 $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code,
967 $mode, $level, $debuginfo);
969 $this->PEAR_Error("DB Error: $code", DB_ERROR,
970 $mode, $level, $debuginfo);
978 // {{{ class DB_result
981 * This class implements a wrapper for a DB result set
983 * A new instance of this class will be returned by the DB implementation
984 * after processing a query that returns data.
988 * @author Stig Bakken <ssb@php.net>
989 * @copyright 1997-2007 The PHP Group
990 * @license http://www.php.net/license/3_0.txt PHP License 3.0
991 * @version Release: 1.8.2
992 * @link http://pear.php.net/package/DB
999 * Should results be freed automatically when there are no more rows?
1001 * @see DB_common::$options
1006 * A reference to the DB_<driver> object
1012 * The current default fetch mode
1014 * @see DB_common::$fetchmode
1019 * The name of the class into which results should be fetched when
1020 * DB_FETCHMODE_OBJECT is in effect
1023 * @see DB_common::$fetchmode_object_class
1025 var $fetchmode_object_class;
1028 * The number of rows to fetch from a limit query
1031 var $limit_count = null;
1034 * The row to start fetching from in limit queries
1037 var $limit_from = null;
1040 * The execute parameters that created this result
1042 * @since Property available since Release 1.7.0
1047 * The query string that created this result
1049 * Copied here incase it changes in $dbh, which is referenced
1052 * @since Property available since Release 1.7.0
1057 * The query result resource id created by PHP
1063 * The present row being dealt with
1066 var $row_counter = null;
1069 * The prepared statement resource id created by PHP in $dbh
1071 * This resource is only available when the result set was created using
1072 * a driver's native execute() method, not PEAR DB's emulated one.
1074 * Copied here incase it changes in $dbh, which is referenced
1076 * {@internal Mainly here because the InterBase/Firebird API is only
1077 * able to retrieve data from result sets if the statemnt handle is
1081 * @since Property available since Release 1.7.0
1090 * This constructor sets the object's properties
1092 * @param object &$dbh the DB object reference
1093 * @param resource $result the result resource id
1094 * @param array $options an associative array with result options
1098 function DB_result(&$dbh, $result, $options = array())
1100 $this->autofree = $dbh->options['autofree'];
1102 $this->fetchmode = $dbh->fetchmode;
1103 $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1104 $this->parameters = $dbh->last_parameters;
1105 $this->query = $dbh->last_query;
1106 $this->result = $result;
1107 $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1108 foreach ($options as $key => $value) {
1109 $this->setOption($key, $value);
1114 * Set options for the DB_result object
1116 * @param string $key the option to set
1117 * @param mixed $value the value to set the option to
1121 function setOption($key, $value = null)
1125 $this->limit_from = $value;
1128 $this->limit_count = $value;
1136 * Fetch a row of data and return it by reference into an array
1138 * The type of array returned can be controlled either by setting this
1139 * method's <var>$fetchmode</var> parameter or by changing the default
1140 * fetch mode setFetchMode() before calling this method.
1142 * There are two options for standardizing the information returned
1143 * from databases, ensuring their values are consistent when changing
1144 * DBMS's. These portability options can be turned on when creating a
1145 * new DB object or by using setOption().
1147 * + <var>DB_PORTABILITY_LOWERCASE</var>
1148 * convert names of fields to lower case
1150 * + <var>DB_PORTABILITY_RTRIM</var>
1151 * right trim the data
1153 * @param int $fetchmode the constant indicating how to format the data
1154 * @param int $rownum the row number to fetch (index starts at 0)
1156 * @return mixed an array or object containing the row's data,
1157 * NULL when the end of the result set is reached
1158 * or a DB_Error object on failure.
1160 * @see DB_common::setOption(), DB_common::setFetchMode()
1162 function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1164 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1165 $fetchmode = $this->fetchmode;
1167 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1168 $fetchmode = DB_FETCHMODE_ASSOC;
1169 $object_class = $this->fetchmode_object_class;
1171 if (is_null($rownum) && $this->limit_from !== null) {
1172 if ($this->row_counter === null) {
1173 $this->row_counter = $this->limit_from;
1175 if ($this->dbh->features['limit'] === false) {
1177 while ($i++ < $this->limit_from) {
1178 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1182 if ($this->row_counter >= ($this->limit_from + $this->limit_count))
1184 if ($this->autofree) {
1190 if ($this->dbh->features['limit'] === 'emulate') {
1191 $rownum = $this->row_counter;
1193 $this->row_counter++;
1195 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1196 if ($res === DB_OK) {
1197 if (isset($object_class)) {
1198 // The default mode is specified in the
1199 // DB_common::fetchmode_object_class property
1200 if ($object_class == 'stdClass') {
1201 $arr = (object) $arr;
1203 $arr = new $object_class($arr);
1208 if ($res == null && $this->autofree) {
1218 * Fetch a row of data into an array which is passed by reference
1220 * The type of array returned can be controlled either by setting this
1221 * method's <var>$fetchmode</var> parameter or by changing the default
1222 * fetch mode setFetchMode() before calling this method.
1224 * There are two options for standardizing the information returned
1225 * from databases, ensuring their values are consistent when changing
1226 * DBMS's. These portability options can be turned on when creating a
1227 * new DB object or by using setOption().
1229 * + <var>DB_PORTABILITY_LOWERCASE</var>
1230 * convert names of fields to lower case
1232 * + <var>DB_PORTABILITY_RTRIM</var>
1233 * right trim the data
1235 * @param array &$arr the variable where the data should be placed
1236 * @param int $fetchmode the constant indicating how to format the data
1237 * @param int $rownum the row number to fetch (index starts at 0)
1239 * @return mixed DB_OK if a row is processed, NULL when the end of the
1240 * result set is reached or a DB_Error object on failure
1242 * @see DB_common::setOption(), DB_common::setFetchMode()
1244 function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1246 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1247 $fetchmode = $this->fetchmode;
1249 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1250 $fetchmode = DB_FETCHMODE_ASSOC;
1251 $object_class = $this->fetchmode_object_class;
1253 if (is_null($rownum) && $this->limit_from !== null) {
1254 if ($this->row_counter === null) {
1255 $this->row_counter = $this->limit_from;
1257 if ($this->dbh->features['limit'] === false) {
1259 while ($i++ < $this->limit_from) {
1260 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1264 if ($this->row_counter >= (
1265 $this->limit_from + $this->limit_count))
1267 if ($this->autofree) {
1272 if ($this->dbh->features['limit'] === 'emulate') {
1273 $rownum = $this->row_counter;
1276 $this->row_counter++;
1278 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1279 if ($res === DB_OK) {
1280 if (isset($object_class)) {
1281 // default mode specified in the
1282 // DB_common::fetchmode_object_class property
1283 if ($object_class == 'stdClass') {
1284 $arr = (object) $arr;
1286 $arr = new $object_class($arr);
1291 if ($res == null && $this->autofree) {
1301 * Get the the number of columns in a result set
1303 * @return int the number of columns. A DB_Error object on failure.
1307 return $this->dbh->numCols($this->result);
1314 * Get the number of rows in a result set
1316 * @return int the number of rows. A DB_Error object on failure.
1320 if ($this->dbh->features['numrows'] === 'emulate'
1321 && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
1323 if ($this->dbh->features['prepare']) {
1324 $res = $this->dbh->query($this->query, $this->parameters);
1326 $res = $this->dbh->query($this->query);
1328 if (DB::isError($res)) {
1332 while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1337 $count = $this->dbh->numRows($this->result);
1340 /* fbsql is checked for here because limit queries are implemented
1341 * using a TOP() function, which results in fbsql_num_rows still
1342 * returning the total number of rows that would have been returned,
1343 * rather than the real number. As a result, we'll just do the limit
1344 * calculations for fbsql in the same way as a database with emulated
1345 * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1346 * because that only gets the result resource, rather than the full
1347 * DB_Result object. */
1348 if (($this->dbh->features['limit'] === 'emulate'
1349 && $this->limit_from !== null)
1350 || $this->dbh->phptype == 'fbsql') {
1351 $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1352 if ($count < $this->limit_from) {
1354 } elseif ($count < ($this->limit_from + $limit_count)) {
1355 $count -= $this->limit_from;
1357 $count = $limit_count;
1368 * Get the next result if a batch of queries was executed
1370 * @return bool true if a new result is available or false if not
1372 function nextResult()
1374 return $this->dbh->nextResult($this->result);
1381 * Frees the resources allocated for this result set
1383 * @return bool true on success. A DB_Error object on failure.
1387 $err = $this->dbh->freeResult($this->result);
1388 if (DB::isError($err)) {
1391 $this->result = false;
1392 $this->statement = false;
1400 * @see DB_common::tableInfo()
1401 * @deprecated Method deprecated some time before Release 1.2
1403 function tableInfo($mode = null)
1405 if (is_string($mode)) {
1406 return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1408 return $this->dbh->tableInfo($this, $mode);
1415 * Determine the query string that created this result
1417 * @return string the query string
1419 * @since Method available since Release 1.7.0
1423 return $this->query;
1427 // {{{ getRowCounter()
1430 * Tells which row number is currently being processed
1432 * @return integer the current row being looked at. Starts at 1.
1434 function getRowCounter()
1436 return $this->row_counter;
1446 * PEAR DB Row Object
1448 * The object contains a row of data from a result set. Each column's data
1449 * is placed in a property named for the column.
1451 * @category Database
1453 * @author Stig Bakken <ssb@php.net>
1454 * @copyright 1997-2007 The PHP Group
1455 * @license http://www.php.net/license/3_0.txt PHP License 3.0
1456 * @version Release: 1.8.2
1457 * @link http://pear.php.net/package/DB
1458 * @see DB_common::setFetchMode()
1465 * The constructor places a row's data into properties of this object
1467 * @param array the array containing the row's data
1471 function DB_row(&$arr)
1473 foreach ($arr as $key => $value) {
1474 $this->$key = &$arr[$key];