Zend: Database connection

This tutorial will help you make connection to your database with Zend Framework.
Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a Zend Framework.

Creating config.php file
If you want to use a database in your application, you have to make config.php file which will contain basic database data. Here we will declare host of database, username, password, database name and so on. Put the code below into config.php file and put it in the application/configs folder of your project.

<?php
return array(
'webhost'=>'localhost',
'appName'=>'Zend Framework Database Connection',
'database'=>array(
'host'=>'localhost',
'dbname'=>'zend',
'username'=>'root',
'password'=>''
)
);
?>

Creating index.php file
Now put the code below into index.php in root of your project.

<?php
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', true);
date_default_timezone_set('Europe/London');
$rootDir = dirname(dirname(__FILE__));
set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';
require_once 'Zend/Registry.php';
require_once 'Zend/Db/Adapter/Pdo/Mysql.php';
require_once 'Zend/Config.php';
$config = new Zend_Config(require 'application/configs/config.php');
$title = $config->appName;
$params = $config->database->toArray();
Zend_Registry::set('title',$title);
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$DB->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Registry::set('DB',$DB);
Zend_Controller_Front::run('application/controllers');
?>

We can store database connection object to Zend_Registry as above and use it when we need to database connection using below code:

$db = Zend_Registry::get('DB');

or

 
$registry = Zend_Registry::getInstance();
$db = $registry['DB'];

Enjoy !!