How to connect to database in Zend Framework

There are so many ways that you can connect to database using zend Framework’s own working principle

1.  appliacation.ini

2. Directly in Controller page

1.How do i use application.ini to connect to database

Add details in your application.ini file

resources.db.adapter = “PDO_MYSQL”
resources.db.params.dbname = searchSystem
resources.db.params.username = root
resources.db.params.password =
resources.db.params.host = localhost
resources.db.isDefaultTableAdapter = true

Now to initialize the database instance in any controller action you just need to write only 1 line i.e

1
$db = Zend_Db_Table::getDefaultAdapter();

In this line $db returns the database instance and getDefaultAdapter() gets all the details from application.ini file to connect to the database.We need to write this line in each Action of any controller page that needs database connection.Using this $db we can query database for the application need.

 

2.Directly in Controller page

1
2
3
4
5
6
$connParams = array(
                    "host" => "localhost",
                    "username" => "root",
                    "password" => "",
                    "dbname" => "searchSystem"
                    );
1
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);

In this line $db returns the database instance.But the problem with this line is we have to write this line again and again the each Action of Contoller page.

 

Full working example of Database connection with database query of Zend Framework

Codes in application.ini file

resources.db.adapter = “PDO_MYSQL”
resources.db.params.dbname = searchSystem
resources.db.params.username = root
resources.db.params.password =
resources.db.params.host = localhost
resources.db.isDefaultTableAdapter = true

Codes in UserController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class UserController extends Zend_Controller_Action
{
  public function listAction()
  {
    $db = Zend_Db_Table::getDefaultAdapter();
    $data = array(
                 'user_name' => 'bikashkumars',
                 'user_password' => 'iambikash',
                 'user_full_name' => 'Bikash Kumar Sundaray',
                 'user_email_id' => 'bikashkumars [AT] gmail [DOT] com'
                  );
     $rows_affected = $db->insert('auth_user_list', $data);
     $last_insert_id = $db->lastInsertId();
 
   }
}

In this above example am able to insert data to a table called auth_user_list with columns as user_name, user_password, user_full_name, user_email_id.