PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Connecting to a Database Using an Adapter

This section describes how to create an instance of a database Adapter. This corresponds to making a connection to your RDBMS server from your PHP application.

Using a Zend_Db Adapter Constructor

You can create an instance of an adapter using its constructor. An adapter constructor takes one argument, which is an array of parameters used to declare the connection.

Example 186. Using an Adapter Constructor

<?php
$db 
= new Zend_Db_Adapter_Pdo_Mysql(array(
    
'host'     => '127.0.0.1',
    
'username' => 'webuser',
    
'password' => 'xxxxxxxx',
    
'dbname'   => 'test'
));

Using the Zend_Db Factory

As an alternative to using an adapter constructor directly, you can create an instance of an adapter using the static method Zend_Db::factory(). This method dynamically loads the adapter class file on demand using Zend_Loader::loadClass().

The first argument is a string that names the base name of the adapter class. For example the string 'Pdo_Mysql' corresponds to the class Zend_Db_Adapter_Pdo_Mysql. The second argument is the same array of parameters you would have given to the adapter constructor.

Example 187. Using the Adapter Factory Method

<?php
// We don't need the following statement because the
// Zend_Db_Adapter_Pdo_Mysql file will be loaded for us by the Zend_Db
// factory method.

// require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

// Automatically load class Zend_Db_Adapter_Pdo_Mysql
// and create an instance of it.
$db Zend_Db::factory('Pdo_Mysql', array(
    
'host'     => '127.0.0.1',
    
'username' => 'webuser',
    
'password' => 'xxxxxxxx',
    
'dbname'   => 'test'
));

If you create your own class that extends Zend_Db_Adapter_Abstract, but you do not name your class with the "Zend_Db_Adapter" package prefix, you can use the factory() method to load your adapter if you specify the leading portion of the adapter class with the 'adapterNamespace' key in the parameters array.

Example 188. Using the Adapter Factory Method for a Custom Adapter Class

<?php
// We don't need to load the adapter class file
// because it will be loaded for us by the Zend_Db factory method.

// Automatically load class MyProject_Db_Adapter_Pdo_Mysql and create
// an instance of it.
$db Zend_Db::factory('Pdo_Mysql', array(
    
'host'             => '127.0.0.1',
    
'username'         => 'webuser',
    
'password'         => 'xxxxxxxx',
    
'dbname'           => 'test',
    
'adapterNamespace' => 'MyProject_Db_Adapter'
));

Using Zend_Config with the Zend_Db Factory

Optionally, you may specify either argument of the factory() method as an object of type Zend_Config.

If the first argument is a config object, it is expected to contain a property named adapter, containing the string naming the adapter class name base. Optionally, the object may contain a property named params, with subproperties corresponding to adapter parameter names. This is used only if the second argument of the factory() method is absent.

Example 189. Using the Adapter Factory Method with a Zend_Config Object

In the example below, a Zend_Config object is created from an array. You can also load data from an external file using classes such as Zend_Config_Ini and Zend_Config_Xml.

<?php
$config 
= new Zend_Config(
    array(
        
'database' => array(
            
'adapter' => 'Mysqli',
            
'params'  => array(
                
'host'     => '127.0.0.1',
                
'dbname'   => 'test',
                
'username' => 'webuser',
                
'password' => 'secret',
            )
        )
    )
);

$db Zend_Db::factory($config->database);

The second argument of the factory() method may be an associative array containing entries corresponding to adapter parameters. This argument is optional. If the first argument is of type Zend_Config, it is assumed to contain all parameters, and the second argument is ignored.

Adapter Parameters

The following list explains common parameters recognized by Zend_Db Adapter classes.

  • host: a string containing a hostname or IP address of the database server. If the database is running on the same host as the PHP application, you may use 'localhost' or '127.0.0.1'.

  • username: account identifier for authenticating a connection to the RDBMS server.

  • password: account password credential for authenticating a connection to the RDBMS server.

  • dbname: database instance name on the RDBMS server.

  • port: some RDBMS servers can accept network connections on a administrator-specified port number. The port parameter allow you to specify the port to which your PHP application connects, to match the port configured on the RDBMS server.

  • charset: specify the charset used for the connection.

  • options: this parameter is an associative array of options that are generic to all Zend_Db_Adapter classes.

  • driver_options: this parameter is an associative array of additional options that are specific to a given database extension. One typical use of this parameter is to set attributes of a PDO driver.

  • adapterNamespace: names the initial part of the class name for the adapter, instead of 'Zend_Db_Adapter'. Use this if you need to use the factory() method to load a non-Zend database adapter class.

  • socket: allows you to specify the socket or named pipe to use. Currently supported only by mysqli adapter.

Example 190. Passing the Case-Folding Option to the Factory

You can specify this option by the constant Zend_Db::CASE_FOLDING. This corresponds to the ATTR_CASE attribute in PDO and IBM DB2 database drivers, adjusting the case of string keys in query result sets. The option takes values Zend_Db::CASE_NATURAL (the default), Zend_Db::CASE_UPPER, and Zend_Db::CASE_LOWER.

<?php
$options 
= array(
    
Zend_Db::CASE_FOLDING => Zend_Db::CASE_UPPER
);

$params = array(
    
'host'           => '127.0.0.1',
    
'username'       => 'webuser',
    
'password'       => 'xxxxxxxx',
    
'dbname'         => 'test',
    
'options'        => $options
);

$db Zend_Db::factory('Db2'$params);

Example 191. Passing the Auto-Quoting Option to the Factory

You can specify this option by the constant Zend_Db::AUTO_QUOTE_IDENTIFIERS. If the value is TRUE (the default), identifiers like table names, column names, and even aliases are delimited in all SQL syntax generated by the Adapter object. This makes it simple to use identifiers that contain SQL keywords, or special characters. If the value is FALSE, identifiers are not delimited automatically. If you need to delimit identifiers, you must do so yourself using the quoteIdentifier() method.

<?php
$options 
= array(
    
Zend_Db::AUTO_QUOTE_IDENTIFIERS => false
);

$params = array(
    
'host'           => '127.0.0.1',
    
'username'       => 'webuser',
    
'password'       => 'xxxxxxxx',
    
'dbname'         => 'test',
    
'options'        => $options
);

$db Zend_Db::factory('Pdo_Mysql'$params);

Example 192. Passing PDO Driver Options to the Factory

<?php
$pdoParams 
= array(
    
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
);

$params = array(
    
'host'           => '127.0.0.1',
    
'username'       => 'webuser',
    
'password'       => 'xxxxxxxx',
    
'dbname'         => 'test',
    
'driver_options' => $pdoParams
);

$db Zend_Db::factory('Pdo_Mysql'$params);

echo 
$db->getConnection()
        ->
getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY);

Example 193. Passing Serialization Options to the Factory

<?php
$options 
= array(
    
Zend_Db::ALLOW_SERIALIZATION => false
);

$params = array(
    
'host'           => '127.0.0.1',
    
'username'       => 'webuser',
    
'password'       => 'xxxxxxxx',
    
'dbname'         => 'test',
    
'options'        => $options
);

$db Zend_Db::factory('Pdo_Mysql'$params);

Managing Lazy Connections

Creating an instance of an Adapter class does not immediately connect to the RDBMS server. The Adapter saves the connection parameters, and makes the actual connection on demand, the first time you need to execute a query. This ensures that creating an Adapter object is quick and inexpensive. You can create an instance of an Adapter even if you are not certain that you need to run any database queries during the current request your application is serving.

If you need to force the Adapter to connect to the RDBMS, use the getConnection() method. This method returns an object for the connection as represented by the respective PHP database extension. For example, if you use any of the Adapter classes for PDO drivers, then getConnection() returns the PDO object, after initiating it as a live connection to the specific database.

It can be useful to force the connection if you want to catch any exceptions it throws as a result of invalid account credentials, or other failure to connect to the RDBMS server. These exceptions are not thrown until the connection is made, so it can help simplify your application code if you handle the exceptions in one place, instead of at the time of the first query against the database.

Additionally, an adapter can get serialized to store it, for example, in a session variable. This can be very useful not only for the adapter itself, but for other objects that aggregate it, like a Zend_Db_Select object. By default, adapters are allowed to be serialized, if you don't want it, you should consider passing the Zend_Db::ALLOW_SERIALIZATION option with FALSE, see the example above. To respect lazy connections principle, the adapter won't reconnect itself after being unserialized. You must then call getConnection() yourself. You can make the adapter auto-reconnect by passing the Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE with TRUE as an adapter option.

Example 194. Handling Connection Exceptions

<?php
try {
    
$db Zend_Db::factory('Pdo_Mysql'$parameters);
    
$db->getConnection();
} catch (
Zend_Db_Adapter_Exception $e) {
    
// perhaps a failed login credential, or perhaps the RDBMS is not running
} catch (Zend_Exception $e) {
    
// perhaps factory() failed to load the specified Adapter class
}

Zend Framework