Connecting

Connecting – Connecting and disconnecting a database

Description

To instantiate a database object you have several methods available using MDB2.

Connection functions
Function Summary Description
factory() Efficient Will instantiate a new MDB2_Driver_Common instance, but will not connect to the database until required. This will delay making the actual connection. This is called lazy connecting. Using this makes sense if it is possible that due to caching inside the application no connection will ever need to be established.
connect() Eager Will instantiate a new MDB2_Driver_Common instance, and will establish a database connection immediately. This way any connection issues will immediately raise an error.
singleton() Available Returns a MDB2_Driver_Common instance. A new MDB2_Driver_Common object is only created once using factory(), subsequent calls to singleton will return a reference to the existing object. This method is preferred over declaring your database object as a global.

To connect to a database you have to use the function factory(), connect() or singleton(), which require a valid DSN as the first parameter. This parameter can either be a string or an array. If using an array, the array used gets merged with the default information:

$dsn = array(
    'phptype'  => false,
    'dbsyntax' => false,
    'username' => false,
    'password' => false,
    'protocol' => false,
    'hostspec' => false,
    'port'     => false,
    'socket'   => false,
    'database' => false,
    'new_link' => false,
    'service'  => false, // only in oci8
);

Any elements you set override the defaults and the remainder stay at their defaults.

The second parameter is the optional $options array that can contain runtime configuration settings for this package.

List of options
Name Type Description
ssl boolean determines if ssl should be used for connections
field_case integer CASE_LOWER|CASE_UPPER: determines what case to force on field/table names
disable_query boolean determines if queries should be executed
result_class string class used for result sets
buffered_result_class string class used for buffered result sets, default is MDB2_Result_Common
result_wrap_class string class used to wrap result sets into, default is MDB2_Result_Common
result_buffering boolean should results be buffered or not?
fetch_class string class to use when fetch mode object is used
persistent boolean persistent connection?
debug integer numeric debug level
debug_handler string function/method that captures debug messages
debug_expanded_output boolean BC option to determine if more context information should be send to the debug handler
default_text_field_length integer default text field length to use
lob_buffer_length integer LOB buffer length
log_line_break string line-break format
idxname_format string pattern with '%s' for index name
seqname_format string pattern with '%s' for sequence name
savepoint_format string pattern with '%s' for auto generated savepoint names
seqcol_name string sequence column name
quote_identifier boolean if identifier quoting should be done when check_option is used
use_transactions boolean if transaction use should be enabled
decimal_places integer number of decimal places to handle
portability integer portability constant
modules array short to long module name mapping for __call()
emulate_prepared boolean force prepared statements to be emulated
datatype_map array map user defined datatypes to other primitive datatypes
datatype_map_callback array callback function/method that should be called

In case of success you get a new instance of the database class. It is strongly recommended to check this return value with PEAR::isError() (will detect PEAR_Error or any subclass) or the MDB2_Driver_Common specific isError().

To disconnect use the method disconnect() from your database class instance.

Connect and disconnect

<?php
require_once 'MDB2.php';

$dsn 'pgsql://someuser:apasswd@localhost/thedb';
$options = array(
    
'debug' => 2,
    
'result_buffering' => false,
);

$mdb2 =& MDB2::factory($dsn$options);
if (
PEAR::isError($mdb2)) {
    die(
$mdb2->getMessage());
}

// ...

$mdb2->disconnect();
?>

Connect using an array for the DSN information

<?php
require_once 'MDB2.php';

$dsn = array(
    
'phptype'  => 'pgsql',
    
'username' => 'someuser',
    
'password' => 'apasswd',
    
'hostspec' => 'localhost',
    
'database' => 'thedb',
);

$options = array(
    
'debug'       => 2,
    
'portability' => MDB2_PORTABILITY_ALL,
);

// uses MDB2::factory() to create the instance
// and also attempts to connect to the host
$mdb2 =& MDB2::connect($dsn$options);
if (
PEAR::isError($mdb2)) {
    die(
$mdb2->getMessage());
}
?>

When connecting to SQLite using a DSN array, the value of the mode element must be a string:

<?php
$dsn 
= array(
    
'phptype'  => 'sqlite',
    
'database' => 'thedb',
    
'mode'     => '0644',
);
?>

Connect to MySQLi via SSL using an array for the DSN information

The ssl element of the $options array must be set to TRUE in order for SSL to work. Each of the extra elements in the $dsn array (key through cipher in the example below) are optional.

<?php
require_once 'MDB2.php';

$dsn = array(
    
'phptype'  => 'mysqli',
    
'username' => 'someuser',
    
'password' => 'apasswd',
    
'hostspec' => 'localhost',
    
'database' => 'thedb',
    
'key'      => 'client-key.pem',
    
'cert'     => 'client-cert.pem',
    
'ca'       => 'cacert.pem',
    
'capath'   => '/path/to/ca/dir',
    
'cipher'   => 'AES',
);

$options = array(
    
'ssl' => true,
);

// gets an existing instance with the same DSN
// otherwise create a new instance using MDB2::factory()
$mdb2 =& MDB2::singleton($dsn$options);
if (
PEAR::isError($mdb2)) {
    die(
$mdb2->getMessage());
}
?>

Connect to a PostgreSQL database via a socket

<?php
require_once 'MDB2.php';

$dsn 'pgsql://someuser:apasswd@unix(/tmp)/thedb';
$options = array(
    
'debug'       => 2,
    
'portability' => MDB2_PORTABILITY_ALL,
);

$mdb2 =& MDB2::factory($dsn$options);
if (
PEAR::isError($mdb2)) {
    die(
$mdb2->getMessage());
}
?>

Connect using singleton

<?php
require_once 'MDB2.php';

$dsn 'pgsql://someuser:apasswd@localhost/thedb';

$mdb2 =& MDB2::singleton($dsn);
if (
PEAR::isError($mdb2)) {
    die(
$mdb2->getMessage());
}

$blah =& new blah();
// is able to use the existing database connection
$blah->foo();

$mdb2->disconnect();

class 
blah
{
    function 
foo() {
        
// get a reference to the existing database object
        
$mdb2 =& MDB2::singleton();
        
// ...
    
}
}
?>
The Data Source Name (Previous) Performing queries (Next)
Last updated: Sun, 23 Nov 2014 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report or add a note.
View this page in:

User Notes:

Note by: user@example.com
I use php5 and none of this seems to work.
Note by: Trung
When using a DSN of type array with the Oracle database, do not specify a 'database' and a 'service'.

Only specify a 'service' as providing both will result in a connection failure.
Note by: uwe.hausdorff@interone.de
I had to change some pear sources manually as the oracle parameters NLS_NUMERIC_CHARATERS and NLS_DATE_FORMAT are not editable by the configuration parameters.

The setting NLS_DATE_FORMAT is disabled by default, NLS_NUMERIC_CHARATERS are always set. This setting is not european standard and may override individual application settings!

see /MDB2/oci8.php in class MDB2_Driver_oci8, function _doConnect on line 395.
My file is version "oci8.php,v 1.192 2007/03/04 22:27:11 quipo Exp"

if (empty($this->dsn['disable_iso_date'])) {
$query = "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'";
$err =& $this->_doQuery($query, true, $connection);
if (PEAR::isError($err)) {
$this->disconnect(false);
return $err;
}
}

$query = "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='. '";
$err =& $this->_doQuery($query, true, $connection);
if (PEAR::isError($err)) {
$this->disconnect(false);
return $err;
}
Note by: CJ
A helpful note that took me days to figure out:

When connecting to a MSSQL database, specify the hostname as: "my.host.name,PORT". Don't use a colon, use a comma. That took so long!
Note by: user@example.com
In PHP5 all objects are passed by reference similar to the way Java does it.

From: http://www.php.net/manual/en/language.oop5.basic.php

"When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it."
Note by: purej
Is this really true here ?
Quote: "new return reference automatically"
When i read it correctly its just for explicit usage of "new" but thats not the case, we use the Factory methods to get our MDB2 Object.
Note by: user@example.com
Note that using =& to assign objects is deprecated in PHP5:
"Since PHP 5, new return reference automatically so using =& in this context is deprecated and produces E_STRICT level message."