Source for file MDB.php
Documentation is available at MDB.php
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox, |
// | Stig. S. Bakken, Lukas Smith |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Author: Lukas Smith <smith@backendmedia.com> |
// +----------------------------------------------------------------------+
// $Id: MDB.php,v 1.59.4.12 2004/02/28 10:37:54 quipo Exp $
require_once('PEAR.php');
* The method mapErrorCode in each MDB_dbtype implementation maps
* native error codes to one of these.
* If you add an error code here, make sure you also add a textual
* version of it in MDB::errorMessage().
define('MDB_ERROR_SYNTAX', -2 );
define('MDB_ERROR_CONSTRAINT', -3 );
define('MDB_ERROR_NOT_FOUND', -4 );
define('MDB_ERROR_ALREADY_EXISTS', -5 );
define('MDB_ERROR_UNSUPPORTED', -6 );
define('MDB_ERROR_MISMATCH', -7 );
define('MDB_ERROR_INVALID', -8 );
define('MDB_ERROR_NOT_CAPABLE', -9 );
define('MDB_ERROR_TRUNCATED', -10 );
define('MDB_ERROR_INVALID_NUMBER', -11 );
define('MDB_ERROR_INVALID_DATE', -12 );
define('MDB_ERROR_DIVZERO', -13 );
define('MDB_ERROR_NODBSELECTED', -14 );
define('MDB_ERROR_CANNOT_CREATE', -15 );
define('MDB_ERROR_CANNOT_DELETE', -16 );
define('MDB_ERROR_CANNOT_DROP', -17 );
define('MDB_ERROR_NOSUCHTABLE', -18 );
define('MDB_ERROR_NOSUCHFIELD', -19 );
define('MDB_ERROR_NEED_MORE_DATA', -20 );
define('MDB_ERROR_NOT_LOCKED', -21 );
define('MDB_ERROR_VALUE_COUNT_ON_ROW', -22 );
define('MDB_ERROR_INVALID_DSN', -23 );
define('MDB_ERROR_CONNECT_FAILED', -24 );
define('MDB_ERROR_EXTENSION_NOT_FOUND',-25 );
define('MDB_ERROR_NOSUCHDB', -26 );
define('MDB_ERROR_ACCESS_VIOLATION', -27 );
define('MDB_ERROR_CANNOT_REPLACE', -28 );
define('MDB_ERROR_CONSTRAINT_NOT_NULL',-29 );
define('MDB_ERROR_DEADLOCK', -30 );
define('MDB_ERROR_CANNOT_ALTER', -31 );
define('MDB_ERROR_MANAGER', -32 );
define('MDB_ERROR_MANAGER_PARSE', -33 );
define('MDB_ERROR_LOADMODULE', -34 );
define('MDB_ERROR_INSUFFICIENT_DATA', -35 );
* This is a special constant that tells DB the user hasn't specified
* any particular get mode, so the default should be used.
define('MDB_FETCHMODE_DEFAULT', 0 );
* Column data indexed by numbers, ordered from 0 and up
define('MDB_FETCHMODE_ORDERED', 1 );
* Column data indexed by column names
define('MDB_FETCHMODE_ASSOC', 2 );
* For multi-dimensional results: normally the first level of arrays
* is the row number, and the second level indexed by column number or name.
* MDB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
* is the column name, and the second level the row number.
define('MDB_FETCHMODE_FLIPPED', 4 );
* These are constants for the tableInfo-function
* they are bitwised or'ed. so if there are more constants to be defined
* in the future, adjust MDB_TABLEINFO_FULL accordingly
define('MDB_TABLEINFO_ORDER', 1 );
define('MDB_TABLEINFO_ORDERTABLE', 2 );
define('MDB_TABLEINFO_FULL', 3 );
* These are constants for each of the supported datatypes
define('MDB_TYPE_BOOLEAN' , 1 );
define('MDB_TYPE_INTEGER' , 2 );
define('MDB_TYPE_DECIMAL' , 3 );
define('MDB_TYPE_TIMESTAMP' , 7 );
* These are global variables that are used to track the various class instances
$GLOBALS['_MDB_lobs'] = array ();
$GLOBALS['_MDB_databases'] = array ();
* The main 'MDB' class is simply a container class with some static
* methods for creating DB objects as well as some utility functions
* common to all parts of DB.
* The object model of DB is as follows (indentation means inheritance):
* MDB The main DB class. This is simply a utility class
* with some 'static' methods for creating MDB objects as
* well as common utility functions for other MDB classes.
* MDB_common The base for each DB implementation. Provides default
* | implementations (in OO lingo virtual methods) for
* | the actual DB implementations as well as a bunch of
* | query utility functions.
* +-MDB_mysql The DB implementation for MySQL. Inherits MDB_Common.
* When calling MDB::factory or MDB::connect for MySQL
* connections, the object returned is an instance of this
* +-MDB_pgsql The DB implementation for PostGreSQL. Inherits MDB_Common.
* When calling MDB::factory or MDB::connect for PostGreSQL
* connections, the object returned is an instance of this
* MDB_Date This class provides several method to convert from and to
* MDB_Manager This class handles the xml schema management.
* @version $Id: MDB.php,v 1.59.4.12 2004/02/28 10:37:54 quipo Exp $
* @author Lukas Smith <smith@backendmedia.com>
* set option array in an exiting database object
* @param object $db MDB object
* @param mixed $options An associative array of option names and
foreach($options as $option => $value) {
$test = $db->setOption ($option, $value);
$db->setOption ('persistent', $options);
$include_lob = $db->getOption ('includelob');
$db->loadLob ('load at start');
$includemanager = $db->getOption ('includemanager');
if(!MDB::isError($includemanager) && $includemanager) {
$db->loadManager ('load at start');
$debug = $db->getOption ('debug');
$db->captureDebugOutput (TRUE );
* Create a new DB connection object for the specified database
* IMPORTANT: In order for MDB to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
* $mdb =& MDB::factory($dsn);
* $mdb = MDB::factory($dsn);
* @param string $type database type, for example 'mysql'
* @return mixed a newly created MDB connection object, or a MDB
$class_name = " MDB_$type";
@include_once(" MDB/${type}.php" );
* Create a new MDB connection object and connect to the specified
* IMPORTANT: In order for MDB to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
* $mdb =& MDB::connect($dsn);
* $mdb = MDB::connect($dsn);
* @param mixed $dsn 'data source name', see the MDB::parseDSN
* method for a description of the dsn format.
* Can also be specified as an array of the
* format returned by MDB::parseDSN.
* @param mixed $options An associative array of option names and
* @return mixed a newly created MDB connection object, or a MDB
function &connect($dsn, $options = FALSE )
if(isset ($dsninfo['phptype'])) {
$type = $dsninfo['phptype'];
$class_name = 'MDB_'. $type;
$include = 'MDB/'. $type. '.php';
NULL , NULL , 'no RDBMS driver specified',
&& isset ($options['debug'])
&& $options['debug'] >= 2
// expose php errors with sufficient debug level
'Unable to include the '. $include. ' file', 'MDB_Error', TRUE );
@$db = & new $class_name();
if(isset ($dsninfo['database'])) {
* Returns a MDB connection with the requested DSN.
* A newnew MDB connection object is only created if no object with the
* reuested DSN exists yet.
* IMPORTANT: In order for MDB to work properly it is necessary that
* you make sure that you work with a reference of the original
* object instead of a copy (this is a PHP4 quirk).
* $mdb =& MDB::sngleton($dsn);
* $mdb = MDB::singleton($dsn);
* @param mixed $dsn 'data source name', see the MDB::parseDSN
* method for a description of the dsn format.
* Can also be specified as an array of the
* format returned by MDB::parseDSN.
* @param mixed $options An associative array of option names and
* @return mixed a newly created MDB connection object, or a MDB
function &singleton($dsn = NULL , $options = FALSE )
$dsninfo_default = array (
for ($i=0 , $j= count($keys); $i< $j; ++ $i) {
$tmp_dsn = $GLOBALS['_MDB_databases'][$keys[$i]]->getDSN ('array');
if ($dsninfo['phptype'] == $tmp_dsn['phptype']
&& $dsninfo['username'] == $tmp_dsn['username']
&& $dsninfo['password'] == $tmp_dsn['password']
&& $dsninfo['hostspec'] == $tmp_dsn['hostspec']
&& $dsninfo['database'] == $tmp_dsn['database'])
MDB::setOptions($GLOBALS['_MDB_databases'][$keys[$i]], $options);
return $GLOBALS['_MDB_databases'][$keys[$i]];
if (is_array($GLOBALS['_MDB_databases'])
&& reset($GLOBALS['_MDB_databases'])
$db = & $GLOBALS['_MDB_databases'][key($GLOBALS['_MDB_databases'])];
* load a file (like 'Date.php' or 'Manager.php')
* @return $file name of the file to be included from the MDB dir without
* the '.php' extension (like 'Date' or 'Manager')
@include_once('MDB/'. $file. '.php');
* Return the MDB API version
* @return int the MDB API version number
* Tell whether a result code from a MDB method is an error
* @param int $value result code
* @return boolean whether $value is an MDB_Error
return is_a($value, 'MDB_Error');
* Tell whether a value is a MDB connection
* @param mixed $value value to test
* @return bool whether $value is a MDB connection
return is_a($value, 'MDB_Common');
* Tell whether a query is a data manipulation query (insert,
* update or delete) or a data definition query (create, drop,
* @param string $query the query
* @return boolean whether $query is a data manipulation query
$manips = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|
ALTER|GRANT|REVOKE|LOCK|UNLOCK|ROLLBACK|COMMIT';
if (preg_match('/^\s*"?('. $manips. ')\s+/i', $query)) {
* Return a textual error message for a MDB error code
* @param int $value error code
* @return string error message, or false if the error code was
if (!isset ($errorMessages)) {
$value = $value->getCode ();
return(isset ($errorMessages[$value]) ?
$errorMessages[$value] : $errorMessages[MDB_ERROR]);
* Parse a data source name
* A array with the following keys will be returned:
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
* The format of the supplied DSN is in its fullest form:
* phptype(dbsyntax)://username:password@protocol+hostspec/database
* Most variations are allowed:
* phptype://username:password@protocol+hostspec:110//usr/db_file.db
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* @param string $dsn Data Source Name to be parsed
* @return array an associative array
* @author Tomas V.V.Cox <cox@idecnet.com>
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== FALSE ) {
$dsn = substr($dsn, $pos + 3 );
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1 ];
$parsed['dbsyntax'] = (empty ($arr[2 ])) ? $arr[1 ] : $arr[2 ];
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
// Get (if found): username and password
// $dsn => username:password@protocol+hostspec/database
if (($at = strrpos($dsn,'@')) !== FALSE ) {
if (($pos = strpos($str, ':')) !== FALSE ) {
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database
if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
$proto_opts = (!empty ($match[2 ])) ? $match[2 ] : FALSE;
// $dsn => protocol+hostspec/database (old format)
if (strpos($dsn, '+') !== FALSE ) {
list ($proto, $dsn) = explode('+', $dsn, 2 );
if (strpos($dsn, '/') !== FALSE ) {
list ($proto_opts, $dsn) = explode('/', $dsn, 2 );
// process the different protocol options
$parsed['protocol'] = (!empty ($proto)) ? $proto : 'tcp';
if ($parsed['protocol'] == 'tcp') {
if (strpos($proto_opts, ':') !== FALSE ) {
list ($parsed['hostspec'], $parsed['port']) =
$parsed['hostspec'] = $proto_opts;
} elseif ($parsed['protocol'] == 'unix') {
$parsed['socket'] = $proto_opts;
if (($pos = strpos($dsn, '?')) === FALSE ) {
$parsed['database'] = $dsn;
// /database?param1=value1¶m2=value2
$parsed['database'] = substr($dsn, 0 , $pos);
$dsn = substr($dsn, $pos + 1 );
if (strpos($dsn, '&') !== FALSE ) {
} else { // database?param1=value1
foreach ($opts as $opt) {
list ($key, $value) = explode('=', $opt);
if (!isset ($parsed[$key])) { // don't allow params overwrite
* MDB_Error implements a class for reporting portable database error
* @author Stig Bakken <ssb@fast.no>
* @param mixed $code MDB error code, or string with error message.
* @param integer $mode what 'error mode' to operate in
* @param integer $level what error level to use for
* $mode & PEAR_ERROR_TRIGGER
* @param smixed $debuginfo additional debug info, such as the last query
function MDB_Error($code = MDB_ERROR , $mode = PEAR_ERROR_RETURN ,
$level = E_USER_NOTICE , $debuginfo = NULL )
$mode, $level, $debuginfo);
$this->PEAR_Error (" MDB Error: $code" , MDB_ERROR, $mode, $level,
Documentation generated on Mon, 11 Mar 2019 10:15:26 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|