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 'lib/pear/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);
185 * Database lock timeout exceeded.
187 define('DB_ERROR_LOCK_TIMEOUT', -30);
190 * Database deadlock encountered.
192 define('DB_ERROR_DEADLOCK', -31);
196 // {{{ prepared statement-related
200 * Identifiers for the placeholders used in prepared statements.
201 * @see DB_common::prepare()
205 * Indicates a scalar (<kbd>?</kbd>) placeholder was used
207 * Quote and escape the value as necessary.
209 define('DB_PARAM_SCALAR', 1);
212 * Indicates an opaque (<kbd>&</kbd>) placeholder was used
214 * The value presented is a file name. Extract the contents of that file
215 * and place them in this column.
217 define('DB_PARAM_OPAQUE', 2);
220 * Indicates a misc (<kbd>!</kbd>) placeholder was used
222 * The value should not be quoted or escaped.
224 define('DB_PARAM_MISC', 3);
229 // {{{ binary data-related
233 * The different ways of returning binary data from queries.
237 * Sends the fetched data straight through to output
239 define('DB_BINMODE_PASSTHRU', 1);
242 * Lets you return data as usual
244 define('DB_BINMODE_RETURN', 2);
247 * Converts the data to hex format before returning it
249 * For example the string "123" would become "313233".
251 define('DB_BINMODE_CONVERT', 3);
261 * @see DB_common::setFetchMode()
265 * Indicates the current default fetch mode should be used
266 * @see DB_common::$fetchmode
268 define('DB_FETCHMODE_DEFAULT', 0);
271 * Column data indexed by numbers, ordered from 0 and up
273 define('DB_FETCHMODE_ORDERED', 1);
276 * Column data indexed by column names
278 define('DB_FETCHMODE_ASSOC', 2);
281 * Column data as object properties
283 define('DB_FETCHMODE_OBJECT', 3);
286 * For multi-dimensional results, make the column name the first level
287 * of the array and put the row number in the second level of the array
289 * This is flipped from the normal behavior, which puts the row numbers
290 * in the first level of the array and the column names in the second level.
292 define('DB_FETCHMODE_FLIPPED', 4);
296 * Old fetch modes. Left here for compatibility.
298 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
299 define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
300 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
305 // {{{ tableInfo() && autoPrepare()-related
309 * The type of information to return from the tableInfo() method.
311 * Bitwised constants, so they can be combined using <kbd>|</kbd>
312 * and removed using <kbd>^</kbd>.
314 * @see DB_common::tableInfo()
316 * {@internal Since the TABLEINFO constants are bitwised, if more of them are
317 * added in the future, make sure to adjust DB_TABLEINFO_FULL accordingly.}}
319 define('DB_TABLEINFO_ORDER', 1);
320 define('DB_TABLEINFO_ORDERTABLE', 2);
321 define('DB_TABLEINFO_FULL', 3);
326 * The type of query to create with the automatic query building methods.
327 * @see DB_common::autoPrepare(), DB_common::autoExecute()
329 define('DB_AUTOQUERY_INSERT', 1);
330 define('DB_AUTOQUERY_UPDATE', 2);
335 // {{{ portability modes
341 * Bitwised constants, so they can be combined using <kbd>|</kbd>
342 * and removed using <kbd>^</kbd>.
344 * @see DB_common::setOption()
346 * {@internal Since the PORTABILITY constants are bitwised, if more of them are
347 * added in the future, make sure to adjust DB_PORTABILITY_ALL accordingly.}}
351 * Turn off all portability features
353 define('DB_PORTABILITY_NONE', 0);
356 * Convert names of tables and fields to lower case
357 * when using the get*(), fetch*() and tableInfo() methods
359 define('DB_PORTABILITY_LOWERCASE', 1);
362 * Right trim the data output by get*() and fetch*()
364 define('DB_PORTABILITY_RTRIM', 2);
367 * Force reporting the number of rows deleted
369 define('DB_PORTABILITY_DELETE_COUNT', 4);
372 * Enable hack that makes numRows() work in Oracle
374 define('DB_PORTABILITY_NUMROWS', 8);
377 * Makes certain error messages in certain drivers compatible
378 * with those from other DBMS's
380 * + mysql, mysqli: change unique/primary key constraints
381 * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
383 * + odbc(access): MS's ODBC driver reports 'no such field' as code
384 * 07001, which means 'too few parameters.' When this option is on
385 * that code gets mapped to DB_ERROR_NOSUCHFIELD.
387 define('DB_PORTABILITY_ERRORS', 16);
390 * Convert null values to empty strings in data output by
391 * get*() and fetch*()
393 define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
396 * Turn on all portability features
398 define('DB_PORTABILITY_ALL', 63);
408 * Database independent query interface
410 * The main "DB" class is simply a container class with some static
411 * methods for creating DB objects as well as some utility functions
412 * common to all parts of DB.
414 * The object model of DB is as follows (indentation means inheritance):
416 * DB The main DB class. This is simply a utility class
417 * with some "static" methods for creating DB objects as
418 * well as common utility functions for other DB classes.
420 * DB_common The base for each DB implementation. Provides default
421 * | implementations (in OO lingo virtual methods) for
422 * | the actual DB implementations as well as a bunch of
423 * | query utility functions.
425 * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
426 * When calling DB::factory or DB::connect for MySQL
427 * connections, the object returned is an instance of this
433 * @author Stig Bakken <ssb@php.net>
434 * @author Tomas V.V.Cox <cox@idecnet.com>
435 * @author Daniel Convissor <danielc@php.net>
436 * @copyright 1997-2007 The PHP Group
437 * @license http://www.php.net/license/3_0.txt PHP License 3.0
438 * @version Release: 1.10.0
439 * @link http://pear.php.net/package/DB
446 * Create a new DB object for the specified database type but don't
447 * connect to the database
449 * @param string $type the database type (eg "mysql")
450 * @param array $options an associative array of option names and values
452 * @return object a new DB object. A DB_Error object on failure.
454 * @see DB_common::setOption()
456 public static function factory($type, $options = false)
458 if (!is_array($options)) {
459 $options = array('persistent' => $options);
462 if (isset($options['debug']) && $options['debug'] >= 2) {
463 // expose php errors with sufficient debug level
464 include_once "DB/{$type}.php";
466 @include_once "DB/{$type}.php";
469 $classname = "DB_${type}";
471 if (!class_exists($classname)) {
472 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
473 "Unable to include the DB/{$type}.php"
474 . " file for '$dsn'",
479 @$obj = new $classname;
481 foreach ($options as $option => $value) {
482 $test = $obj->setOption($option, $value);
483 if (DB::isError($test)) {
495 * Create a new DB object including a connection to the specified database
499 * require_once 'DB.php';
501 * $dsn = 'pgsql://user:password@host/database';
504 * 'portability' => DB_PORTABILITY_ALL,
507 * $db = DB::connect($dsn, $options);
508 * if (PEAR::isError($db)) {
509 * die($db->getMessage());
513 * @param mixed $dsn the string "data source name" or array in the
514 * format returned by DB::parseDSN()
515 * @param array $options an associative array of option names and values
517 * @return object a new DB object. A DB_Error object on failure.
519 * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
520 * DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
521 * DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
522 * DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
523 * DB_sybase::connect()
525 * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
527 public static function connect($dsn, $options = array())
529 $dsninfo = DB::parseDSN($dsn);
530 $type = $dsninfo['phptype'];
532 if (!is_array($options)) {
534 * For backwards compatibility. $options used to be boolean,
535 * indicating whether the connection should be persistent.
537 $options = array('persistent' => $options);
540 if (isset($options['debug']) && $options['debug'] >= 2) {
541 // expose php errors with sufficient debug level
542 include_once "DB/${type}.php";
544 @include_once "DB/${type}.php";
547 $classname = "DB_${type}";
548 if (!class_exists($classname)) {
549 $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
550 "Unable to include the DB/{$type}.php"
552 . DB::getDSNString($dsn, true) . "'",
557 @$obj = new $classname;
559 foreach ($options as $option => $value) {
560 $test = $obj->setOption($option, $value);
561 if (DB::isError($test)) {
566 $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
567 if (DB::isError($err)) {
568 if (is_array($dsn)) {
569 $err->addUserInfo(DB::getDSNString($dsn, true));
571 $err->addUserInfo($dsn);
583 * Return the DB API version
585 * @return string the DB API version number
587 function apiVersion()
596 * Determines if a variable is a DB_Error object
598 * @param mixed $value the variable to check
600 * @return bool whether $value is DB_Error object
602 public static function isError($value)
604 return is_object($value) && is_a($value, 'DB_Error');
608 // {{{ isConnection()
611 * Determines if a value is a DB_<driver> object
613 * @param mixed $value the value to test
615 * @return bool whether $value is a DB_<driver> object
617 public static function isConnection($value)
619 return (is_object($value) &&
620 is_subclass_of($value, 'db_common') &&
621 method_exists($value, 'simpleQuery'));
628 * Tell whether a query is a data manipulation or data definition query
630 * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
631 * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
634 * @param string $query the query
636 * @return boolean whether $query is a data manipulation query
638 public static function isManip($query)
640 $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
642 . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
643 . 'ALTER|GRANT|REVOKE|'
645 if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
652 // {{{ errorMessage()
655 * Return a textual error message for a DB error code
657 * @param integer $value the DB error code
659 * @return string the error message or false if the error code was
662 public static function errorMessage($value)
664 static $errorMessages;
665 if (!isset($errorMessages)) {
666 $errorMessages = array(
667 DB_ERROR => 'unknown error',
668 DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
669 DB_ERROR_ALREADY_EXISTS => 'already exists',
670 DB_ERROR_CANNOT_CREATE => 'can not create',
671 DB_ERROR_CANNOT_DROP => 'can not drop',
672 DB_ERROR_CONNECT_FAILED => 'connect failed',
673 DB_ERROR_CONSTRAINT => 'constraint violation',
674 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
675 DB_ERROR_DIVZERO => 'division by zero',
676 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
677 DB_ERROR_INVALID => 'invalid',
678 DB_ERROR_INVALID_DATE => 'invalid date or time',
679 DB_ERROR_INVALID_DSN => 'invalid DSN',
680 DB_ERROR_INVALID_NUMBER => 'invalid number',
681 DB_ERROR_MISMATCH => 'mismatch',
682 DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
683 DB_ERROR_NODBSELECTED => 'no database selected',
684 DB_ERROR_NOSUCHDB => 'no such database',
685 DB_ERROR_NOSUCHFIELD => 'no such field',
686 DB_ERROR_NOSUCHTABLE => 'no such table',
687 DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
688 DB_ERROR_NOT_FOUND => 'not found',
689 DB_ERROR_NOT_LOCKED => 'not locked',
690 DB_ERROR_SYNTAX => 'syntax error',
691 DB_ERROR_UNSUPPORTED => 'not supported',
692 DB_ERROR_TRUNCATED => 'truncated',
693 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
695 DB_ERROR_DEADLOCK => 'deadlock',
696 DB_ERROR_LOCK_TIMEOUT => 'database lock timeout',
700 if (DB::isError($value)) {
701 $value = $value->getCode();
704 return isset($errorMessages[$value]) ? $errorMessages[$value]
705 : $errorMessages[DB_ERROR];
712 * Parse a data source name
714 * Additional keys can be added by appending a URI query string to the
717 * The format of the supplied DSN is in its fullest form:
719 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
722 * Most variations are allowed:
724 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
725 * phptype://username:password@hostspec/database_name
726 * phptype://username:password@hostspec
727 * phptype://username@hostspec
728 * phptype://hostspec/database
734 * @param string $dsn Data Source Name to be parsed
736 * @return array an associative array with the following keys:
737 * + phptype: Database backend used in PHP (mysql, odbc etc.)
738 * + dbsyntax: Database used with regards to SQL syntax etc.
739 * + protocol: Communication protocol to use (tcp, unix etc.)
740 * + hostspec: Host specification (hostname[:port])
741 * + database: Database to use on the DBMS server
742 * + username: User name for login
743 * + password: Password for login
745 public static function parseDSN($dsn)
759 if (is_array($dsn)) {
760 $dsn = array_merge($parsed, $dsn);
761 if (!$dsn['dbsyntax']) {
762 $dsn['dbsyntax'] = $dsn['phptype'];
767 // Find phptype and dbsyntax
768 if (($pos = strpos($dsn, '://')) !== false) {
769 $str = substr($dsn, 0, $pos);
770 $dsn = substr($dsn, $pos + 3);
776 // Get phptype and dbsyntax
777 // $str => phptype(dbsyntax)
778 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
779 $parsed['phptype'] = $arr[1];
780 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
782 $parsed['phptype'] = $str;
783 $parsed['dbsyntax'] = $str;
790 // Get (if found): username and password
791 // $dsn => username:password@protocol+hostspec/database
792 if (($at = strrpos($dsn,'@')) !== false) {
793 $str = substr($dsn, 0, $at);
794 $dsn = substr($dsn, $at + 1);
795 if (($pos = strpos($str, ':')) !== false) {
796 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
797 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
799 $parsed['username'] = rawurldecode($str);
803 // Find protocol and hostspec
805 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
806 // $dsn => proto(proto_opts)/database
808 $proto_opts = $match[2] ? $match[2] : false;
812 // $dsn => protocol+hostspec/database (old format)
813 if (strpos($dsn, '+') !== false) {
814 list($proto, $dsn) = explode('+', $dsn, 2);
816 if (strpos($dsn, '/') !== false) {
817 list($proto_opts, $dsn) = explode('/', $dsn, 2);
824 // process the different protocol options
825 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
826 $proto_opts = rawurldecode($proto_opts);
827 if (strpos($proto_opts, ':') !== false) {
828 list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
830 if ($parsed['protocol'] == 'tcp') {
831 $parsed['hostspec'] = $proto_opts;
832 } elseif ($parsed['protocol'] == 'unix') {
833 $parsed['socket'] = $proto_opts;
839 if (($pos = strpos($dsn, '?')) === false) {
841 $parsed['database'] = rawurldecode($dsn);
843 // /database?param1=value1¶m2=value2
844 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
845 $dsn = substr($dsn, $pos + 1);
846 if (strpos($dsn, '&') !== false) {
847 $opts = explode('&', $dsn);
848 } else { // database?param1=value1
851 foreach ($opts as $opt) {
852 list($key, $value) = explode('=', $opt);
853 if (!isset($parsed[$key])) {
854 // don't allow params overwrite
855 $parsed[$key] = rawurldecode($value);
865 // {{{ getDSNString()
868 * Returns the given DSN in a string format suitable for output.
870 * @param array|string the DSN to parse and format
871 * @param boolean true to hide the password, false to include it
874 public static function getDSNString($dsn, $hidePassword) {
875 /* Calling parseDSN will ensure that we have all the array elements
876 * defined, and means that we deal with strings and array in the same
878 $dsnArray = DB::parseDSN($dsn);
881 $dsnArray['password'] = 'PASSWORD';
884 /* Protocol is special-cased, as using the default "tcp" along with an
885 * Oracle TNS connection string fails. */
886 if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
887 $dsnArray['protocol'] = false;
890 // Now we just have to construct the actual string. This is ugly.
891 $dsnString = $dsnArray['phptype'];
892 if ($dsnArray['dbsyntax']) {
893 $dsnString .= '('.$dsnArray['dbsyntax'].')';
896 .$dsnArray['username']
898 .$dsnArray['password']
900 .$dsnArray['protocol'];
901 if ($dsnArray['socket']) {
902 $dsnString .= '('.$dsnArray['socket'].')';
904 if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
907 $dsnString .= $dsnArray['hostspec'];
908 if ($dsnArray['port']) {
909 $dsnString .= ':'.$dsnArray['port'];
911 $dsnString .= '/'.$dsnArray['database'];
913 /* Option handling. Unfortunately, parseDSN simply places options into
914 * the top-level array, so we'll first get rid of the fields defined by
915 * DB and see what's left. */
916 unset($dsnArray['phptype'],
917 $dsnArray['dbsyntax'],
918 $dsnArray['username'],
919 $dsnArray['password'],
920 $dsnArray['protocol'],
922 $dsnArray['hostspec'],
924 $dsnArray['database']
926 if (count($dsnArray) > 0) {
929 foreach ($dsnArray as $key => $value) {
933 $dsnString .= $key.'='.$value;
944 // {{{ class DB_Error
947 * DB_Error implements a class for reporting portable database error
952 * @author Stig Bakken <ssb@php.net>
953 * @copyright 1997-2007 The PHP Group
954 * @license http://www.php.net/license/3_0.txt PHP License 3.0
955 * @version Release: 1.10.0
956 * @link http://pear.php.net/package/DB
958 class DB_Error extends PEAR_Error
963 * DB_Error constructor
965 * @param mixed $code DB error code, or string with error message
966 * @param int $mode what "error mode" to operate in
967 * @param int $level what error level to use for $mode &
969 * @param mixed $debuginfo additional debug info, such as the last query
973 function __construct($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
974 $level = E_USER_NOTICE, $debuginfo = null)
977 parent::__construct('DB Error: ' . DB::errorMessage($code), $code,
978 $mode, $level, $debuginfo);
980 parent::__construct("DB Error: $code", DB_ERROR,
981 $mode, $level, $debuginfo);
986 * Workaround to both avoid the "Redefining already defined constructor"
987 * PHP error and provide backward compatibility in case someone is calling
988 * DB_Error() dynamically
990 public function __call($method, $arguments)
992 if ($method == 'DB_Error') {
993 return call_user_func_array(array($this, '__construct'), $arguments);
996 'Call to undefined method DB_Error::' . $method . '()', E_USER_ERROR
1003 // {{{ class DB_result
1006 * This class implements a wrapper for a DB result set
1008 * A new instance of this class will be returned by the DB implementation
1009 * after processing a query that returns data.
1011 * @category Database
1013 * @author Stig Bakken <ssb@php.net>
1014 * @copyright 1997-2007 The PHP Group
1015 * @license http://www.php.net/license/3_0.txt PHP License 3.0
1016 * @version Release: 1.10.0
1017 * @link http://pear.php.net/package/DB
1024 * Should results be freed automatically when there are no more rows?
1026 * @see DB_common::$options
1031 * A reference to the DB_<driver> object
1037 * The current default fetch mode
1039 * @see DB_common::$fetchmode
1044 * The name of the class into which results should be fetched when
1045 * DB_FETCHMODE_OBJECT is in effect
1048 * @see DB_common::$fetchmode_object_class
1050 var $fetchmode_object_class;
1053 * The number of rows to fetch from a limit query
1056 var $limit_count = null;
1059 * The row to start fetching from in limit queries
1062 var $limit_from = null;
1065 * The execute parameters that created this result
1067 * @since Property available since Release 1.7.0
1072 * The query string that created this result
1074 * Copied here incase it changes in $dbh, which is referenced
1077 * @since Property available since Release 1.7.0
1082 * The query result resource id created by PHP
1088 * The present row being dealt with
1091 var $row_counter = null;
1094 * The prepared statement resource id created by PHP in $dbh
1096 * This resource is only available when the result set was created using
1097 * a driver's native execute() method, not PEAR DB's emulated one.
1099 * Copied here incase it changes in $dbh, which is referenced
1101 * {@internal Mainly here because the InterBase/Firebird API is only
1102 * able to retrieve data from result sets if the statemnt handle is
1106 * @since Property available since Release 1.7.0
1115 * This constructor sets the object's properties
1117 * @param object &$dbh the DB object reference
1118 * @param resource $result the result resource id
1119 * @param array $options an associative array with result options
1123 function __construct(&$dbh, $result, $options = array())
1125 $this->autofree = $dbh->options['autofree'];
1127 $this->fetchmode = $dbh->fetchmode;
1128 $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1129 $this->parameters = $dbh->last_parameters;
1130 $this->query = $dbh->last_query;
1131 $this->result = $result;
1132 $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1133 foreach ($options as $key => $value) {
1134 $this->setOption($key, $value);
1139 * Set options for the DB_result object
1141 * @param string $key the option to set
1142 * @param mixed $value the value to set the option to
1146 function setOption($key, $value = null)
1150 $this->limit_from = $value;
1153 $this->limit_count = $value;
1161 * Fetch a row of data and return it by reference into an array
1163 * The type of array returned can be controlled either by setting this
1164 * method's <var>$fetchmode</var> parameter or by changing the default
1165 * fetch mode setFetchMode() before calling this method.
1167 * There are two options for standardizing the information returned
1168 * from databases, ensuring their values are consistent when changing
1169 * DBMS's. These portability options can be turned on when creating a
1170 * new DB object or by using setOption().
1172 * + <var>DB_PORTABILITY_LOWERCASE</var>
1173 * convert names of fields to lower case
1175 * + <var>DB_PORTABILITY_RTRIM</var>
1176 * right trim the data
1178 * @param int $fetchmode the constant indicating how to format the data
1179 * @param int $rownum the row number to fetch (index starts at 0)
1181 * @return mixed an array or object containing the row's data,
1182 * NULL when the end of the result set is reached
1183 * or a DB_Error object on failure.
1185 * @see DB_common::setOption(), DB_common::setFetchMode()
1187 function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1189 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1190 $fetchmode = $this->fetchmode;
1192 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1193 $fetchmode = DB_FETCHMODE_ASSOC;
1194 $object_class = $this->fetchmode_object_class;
1196 if (is_null($rownum) && $this->limit_from !== null) {
1197 if ($this->row_counter === null) {
1198 $this->row_counter = $this->limit_from;
1200 if ($this->dbh->features['limit'] === false) {
1202 while ($i++ < $this->limit_from) {
1203 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1207 if ($this->row_counter >= ($this->limit_from + $this->limit_count))
1209 if ($this->autofree) {
1215 if ($this->dbh->features['limit'] === 'emulate') {
1216 $rownum = $this->row_counter;
1218 $this->row_counter++;
1220 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1221 if ($res === DB_OK) {
1222 if (isset($object_class)) {
1223 // The default mode is specified in the
1224 // DB_common::fetchmode_object_class property
1225 if ($object_class == 'stdClass') {
1226 $arr = (object) $arr;
1228 $arr = new $object_class($arr);
1233 if ($res == null && $this->autofree) {
1243 * Fetch a row of data into an array which is passed by reference
1245 * The type of array returned can be controlled either by setting this
1246 * method's <var>$fetchmode</var> parameter or by changing the default
1247 * fetch mode setFetchMode() before calling this method.
1249 * There are two options for standardizing the information returned
1250 * from databases, ensuring their values are consistent when changing
1251 * DBMS's. These portability options can be turned on when creating a
1252 * new DB object or by using setOption().
1254 * + <var>DB_PORTABILITY_LOWERCASE</var>
1255 * convert names of fields to lower case
1257 * + <var>DB_PORTABILITY_RTRIM</var>
1258 * right trim the data
1260 * @param array &$arr the variable where the data should be placed
1261 * @param int $fetchmode the constant indicating how to format the data
1262 * @param int $rownum the row number to fetch (index starts at 0)
1264 * @return mixed DB_OK if a row is processed, NULL when the end of the
1265 * result set is reached or a DB_Error object on failure
1267 * @see DB_common::setOption(), DB_common::setFetchMode()
1269 function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1271 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1272 $fetchmode = $this->fetchmode;
1274 if ($fetchmode === DB_FETCHMODE_OBJECT) {
1275 $fetchmode = DB_FETCHMODE_ASSOC;
1276 $object_class = $this->fetchmode_object_class;
1278 if (is_null($rownum) && $this->limit_from !== null) {
1279 if ($this->row_counter === null) {
1280 $this->row_counter = $this->limit_from;
1282 if ($this->dbh->features['limit'] === false) {
1284 while ($i++ < $this->limit_from) {
1285 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1289 if ($this->row_counter >= (
1290 $this->limit_from + $this->limit_count))
1292 if ($this->autofree) {
1297 if ($this->dbh->features['limit'] === 'emulate') {
1298 $rownum = $this->row_counter;
1301 $this->row_counter++;
1303 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1304 if ($res === DB_OK) {
1305 if (isset($object_class)) {
1306 // default mode specified in the
1307 // DB_common::fetchmode_object_class property
1308 if ($object_class == 'stdClass') {
1309 $arr = (object) $arr;
1311 $arr = new $object_class($arr);
1316 if ($res == null && $this->autofree) {
1326 * Get the the number of columns in a result set
1328 * @return int the number of columns. A DB_Error object on failure.
1332 return $this->dbh->numCols($this->result);
1339 * Get the number of rows in a result set
1341 * @return int the number of rows. A DB_Error object on failure.
1345 if ($this->dbh->features['numrows'] === 'emulate'
1346 && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
1348 if ($this->dbh->features['prepare']) {
1349 $res = $this->dbh->query($this->query, $this->parameters);
1351 $res = $this->dbh->query($this->query);
1353 if (DB::isError($res)) {
1357 while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1362 $count = $this->dbh->numRows($this->result);
1365 /* fbsql is checked for here because limit queries are implemented
1366 * using a TOP() function, which results in fbsql_num_rows still
1367 * returning the total number of rows that would have been returned,
1368 * rather than the real number. As a result, we'll just do the limit
1369 * calculations for fbsql in the same way as a database with emulated
1370 * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1371 * because that only gets the result resource, rather than the full
1372 * DB_Result object. */
1373 if (($this->dbh->features['limit'] === 'emulate'
1374 && $this->limit_from !== null)
1375 || $this->dbh->phptype == 'fbsql') {
1376 $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1377 if ($count < $this->limit_from) {
1379 } elseif ($count < ($this->limit_from + $limit_count)) {
1380 $count -= $this->limit_from;
1382 $count = $limit_count;
1393 * Get the next result if a batch of queries was executed
1395 * @return bool true if a new result is available or false if not
1397 function nextResult()
1399 return $this->dbh->nextResult($this->result);
1406 * Frees the resources allocated for this result set
1408 * @return bool true on success. A DB_Error object on failure.
1412 $err = $this->dbh->freeResult($this->result);
1413 if (DB::isError($err)) {
1416 $this->result = false;
1417 $this->statement = false;
1425 * @see DB_common::tableInfo()
1426 * @deprecated Method deprecated some time before Release 1.2
1428 function tableInfo($mode = null)
1430 if (is_string($mode)) {
1431 return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1433 return $this->dbh->tableInfo($this, $mode);
1440 * Determine the query string that created this result
1442 * @return string the query string
1444 * @since Method available since Release 1.7.0
1448 return $this->query;
1452 // {{{ getRowCounter()
1455 * Tells which row number is currently being processed
1457 * @return integer the current row being looked at. Starts at 1.
1459 function getRowCounter()
1461 return $this->row_counter;
1471 * PEAR DB Row Object
1473 * The object contains a row of data from a result set. Each column's data
1474 * is placed in a property named for the column.
1476 * @category Database
1478 * @author Stig Bakken <ssb@php.net>
1479 * @copyright 1997-2007 The PHP Group
1480 * @license http://www.php.net/license/3_0.txt PHP License 3.0
1481 * @version Release: 1.10.0
1482 * @link http://pear.php.net/package/DB
1483 * @see DB_common::setFetchMode()
1490 * The constructor places a row's data into properties of this object
1492 * @param array the array containing the row's data
1496 function __construct(&$arr)
1498 foreach ($arr as $key => $value) {
1499 $this->$key = &$arr[$key];