Zend Framework - Different Databases



As discussed in the last chapter, Zend framework provides a generic way to access the database using the Database Driver concept. Working with a database solely depends on the driver information and so, connecting with different database involves just changing the driver information.

Let us now change the book example to connect to the postgresql database with the following steps.

Step 1 − Create a database, tutorials in the local postgresql database using the following command −

CREATE DATABASE tutorials

Step 2 − Add book table. Move to the new database and execute the table creation script.

\c tutorials 
CREATE TABLE book ( 
   id SERIAL NOT NULL, 
   author varchar(100) NOT NULL, 
   title varchar(100) NOT NULL, 
   PRIMARY KEY (id) 
); 

Step 3 − Add sample book information using the following script −

INSERT INTO book (author, title) VALUES ('Dennis Ritchie', 'C Programming'); 
INSERT INTO book (author, title) VALUES ('James gosling', 'Java Programming'); 
INSERT INTO book (author, title) VALUES ('Rasmus Lerdorf', 'Programming PHP');

Step 4 − Change the driver information in the global.config file.

<?php 
return array ( 
   'db' => array ( 
      'driver' => 'Pdo', 
      'dsn' => 'pgsql:dbname = tutorials;host = localhost', 
      'driver_options' => array ( 
      ), 
   ), 
); 

Step 5 − Change the database credentials in the local.config file.

return array ( 
   'db' => array( 
      'username' => '<username>', 
      'password' => '<password>', 
   ), 
);

Step 6 − Finally, run the application http://localhost:8080/tutorial. The result is same as the MySQL application.

Advertisements