Zend Framework – First Database Driven Application – Tutorial

Hey Everybody, I’m back with very interesting tutorial, that is a simple Database Driven Application in Zend Framework. Before I begin, I must tell you I am assuming that you are having Ubuntu installed on your system, and you are known to languages HTML and PHP.
The requirements as under ..
1) Latest version of PHP, MySql Database and Apache Web Server(httpd) are installed on your system.
2) mod_rewrite extension of Apache must be enabled. To enable, do the following (only for Debian based distros, like Ubuntu) :
sudo a2enmod rewrite
and don’t forget to restart Apache.
sudo service apache2 restart
3) A BIG Cup of Coffee.

Lets Start, First of all, make a directory structure like this, project/ must be placed inside the /var/www/ Directory :

project/
——-application/
——————controllers/
——————forms/
——————models/
——————views/
————————-scripts/
———————————-error/
———————————-index/

Directory “project/” is main working directory of the our application. Download Zend Framework minimal package from http://framework.zend.com/download/latest

Then Extract the Library folder inside the archive to our project/ directory, graphically or use following commands (for UBUNTU)
Log in to root and extract ->

$ su -i
$ cd /home/your_username_here/Downloads/
$ tar -xf Zend-minimal.tar.gz

NOTE : directory name: Zend-minimal.tar.gz can vary according to the version of Zend, you downloaded.
Move library directory to project/
$ cd Zend-minimal
$ cp library /var/www/project/library

We have placed the required Zend Framework Files, more interesting thing is the next.
create index.php file inside the project/ directory and write the following code also readout the comments given in the code.
———————————————–
<?php
define(‘ROOT_DIR’, dirname(__FILE__));

//including the MVC (Model-View-Controller) directories and Zend library

set_include_path(‘.’
. PATH_SEPARATOR . ROOT_DIR . ‘/library’
. PATH_SEPARATOR . ROOT_DIR . ‘/application/models’
. PATH_SEPARATOR . ROOT_DIR . ‘/application/forms’
. PATH_SEPARATOR . get_include_path()
);

//Autoloading the zend

require_once “Zend/Loader/Autoloader.php”;
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true)

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(ROOT_DIR.’/application/controllers’);
$frontController->dispatch();
?>
———————————————–
So this was the index.php file, When we will open this file, Zend will lookout for IndexController.php inside the controllers/ directory which we have defined in the index.php file, therefore create the IndexController.php inside project/application/controllers/ and write the following code in it.

NOTE: Be careful about the case of files and codes, all are case-sensitive.
———————————————–
// setting up the controller here..
<?php

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}}

?>
———————————————–
and now the inside the IndexController.php we created the class with the same name, and indexAction() is created. indexAction() will look for index.phtml inside the project/application/views/scripts/index/ so just create it, whatever you will write in this file, directly comes to your view. Similarly create error.phtml in project/application/views/scripts/error/ and write anything that will identify you, whenever you faced the error.
Next, create .htacess file in project/ folder and write following code in it

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

This is the file where mod_rewrite extension of Apache Web Server(httpd) is used to rewrite the URLs, as I will not discuss this now.
Now, I must tell you that we are creating database application to store the basic information of the user into the database and view it. So firstly I’m going to setup the view page. To do so we must create a database and a table inside it
Create a Database and note down the name you created. Create table by executing the following query :

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(75) NOT NULL,
`pname` varchar(75) NOT NULL,
`address` varchar(100) NOT NULL,
`contact` varchar(15) NOT NULL,
`hobbies` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Upto now, the database and table are created, now configure the database settings. Create a file config.ini inside the /project/application/ directory, write the following code, fill in your details and save the file.

[general]
db.adapter = "PDO_MYSQL"
db.params.host = "localhost"
db.params.username = "root"
db.params.password = ""
db.params.dbname = "project"

We have created the Database configuration file, now add the following lines to index.php
———————————————–
$config = new Zend_Config_Ini(ROOT_DIR.’/application/config.ini’, ‘general’);
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);
———————————————–
now it should look like ..
———————————————–
<?php
define(‘ROOT_DIR’, dirname(__FILE__));

set_include_path(‘.’
. PATH_SEPARATOR . ROOT_DIR . ‘/library’
. PATH_SEPARATOR . ROOT_DIR . ‘/application/models’
. PATH_SEPARATOR . ROOT_DIR . ‘/application/forms’
. PATH_SEPARATOR . get_include_path()
);

require_once “Zend/Loader/Autoloader.php”;
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);

//database configs initialized

$config = new Zend_Config_Ini(ROOT_DIR.’/application/config.ini’, ‘general’);
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(ROOT_DIR.’/application/controllers’);
$frontController->dispatch();
?>
———————————————–
I’ve also added a form to view the data in specific defined order as desired by the viewer, So create a file named SortForm.php inside /project/application/forms directory and write following code.
———————————————–
<?php
class SortForm extends Zend_Form
{
public function init()
{

$this->setMethod(‘post’);
$this->addElement(‘radio’, ‘sortby’, array(
‘label’ => ‘Sort by Column:’,
‘multioptions’ => array(
‘name’ => ‘Name’,
‘pname’ => ‘Parent\’s Name’,
‘address’ => ‘Address’,
‘contact’ => ‘Contact’,
‘hobbies’ => ‘hobbies’
),

));

$this->addElement(‘radio’, ‘sorttype’, array(
‘label’ => ‘Sort Type:’,
‘multioptions’ => array(
‘ASC’ => ‘Aescending’,
‘DESC’ => ‘Descending’
),

));
$this->addElement(‘text’,’search’,array(
‘label’=>’search name’));
$this->addElement(‘submit’,’sortdata’,array(
‘label’=>’Sort Data’));

}
}
?>
———————————————–
so We also update the IndexController.php and so as the index.phtml, the respective updated codes are embedded below.
IndexController.php
———————————————–
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{

//loading Users model, ans SortForm
$users = new Users();
$form = new SortForm();
$this->view->form = $form;

//searching and sorting logic
if ($this->getRequest()->isPost()) {
$sortData = $this->_request->getPost();

}
if((empty($sortData[‘search’])==0)){

if(isset($sortData[‘sortby’]) && isset($sortData[‘sorttype’]))
{

$data=$users->fetchAll($users->select()->order($sortData[‘sortby’].” “.$sortData[‘sorttype’])->where(‘name = ?’, $sortData[‘search’]));
}
else
{

$data=$users->fetchAll($users->select()->where(‘name = ?’, $sortData[‘search’]));
}

}

elseif(isset($sortData[‘sortby’]) && isset($sortData[‘sorttype’])){

$data=$users->fetchAll($users->select()->order($sortData[‘sortby’].” “.$sortData[‘sorttype’]));
}

else {

$data = $users->fetchAll($users->select());

}

$this->view->data = $data;
}

}

?>
———————————————–
index.phtml
———————————————–
<h3>All Added Entries</h4>

<?php

echo $this->form;
?>

<table border=”1”>

<tr>
<th>Name</th>
<th>Father’s Name</th>
<th>Address</th>
<th>Contact</th>
<th>Hobbies</th>
</tr>

<?php foreach ($this->data as $d) {?>
<tr>
<td><?php echo $d[‘name’];?></td>
<td><?php echo $d[‘pname’];?></td>
<td><?php echo $d[‘address’];?></td>
<td><?php echo $d[‘contact’];?></td>
<td><?php echo $d[‘hobbies’];?></td>
</tr>
<?php }?>

</table>
———————————————–
We have to setup a model for the Database table which we are using, which is also used in indexAction() of IndexController.php file so, create a file Users.php which resides in /project/application/models/ directory and write the corresponding code.
———————————————–

<?php class Users extends Zend_Db_Table {    protected $_name = “users”; } ?>

———————————————–
also create ErrorController.php inside project/application/controllers/ and write the code, which we are using to display errors if any occurs.
———————————————–
<?php

class ErrorController extends Zend_Controller_Action {

public function errorAction() {
$errors = $this->_getParam(‘error_handler’);
$exception = $errors->exception;

echo $exception->getMessage();
echo “<br /><pre>”;
echo $exception->getTraceAsString();
}
}
?>
———————————————–
NOTE: If you are a beginner with PHP application or you’re facing problems in understanding, you must take a break here, try reading next after sometime.
Next is the Data Entry form for user, create a form named CustomForm.php inside project/application/forms/ directory and write the following code to create a form for Data Entry.
———————————————–
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod(‘post’);

$id = $this->createElement(‘hidden’,’id’);
$name = $this->createElement(‘text’,’name’);
$name->setLabel(‘Name:’)
->setAttrib(‘maxlength’,75);
$pname = $this->createElement(‘text’,’pname’);
$pname->setLabel(‘Father\’s Name’)
->setAttrib(‘maxlength’,75);
$address = $this->createElement(‘text’,’address’);
$address->setLabel(‘Address:’)
->setAttrib(‘maxlength’,100)
->setAttrib(‘size’,75);
$contact = $this->createElement(‘text’,’contact’);
$contact->setLabel(‘Contact:’)
->setAttrib(‘maxlength’,15)
->setAttrib(‘size’,15);

$hobbies = $this->createElement(‘textarea’,’hobbies’);
$hobbies->setLabel(‘Hobbies (seprate with coma(,)):’)
->setAttrib(‘size’,255)
->setAttrib(‘rows’,10)
->setAttrib(‘cols’,40);
$addentry = $this->createElement(‘submit’,’addentry’);
$addentry->setLabel(“Add Entry”)
->setIgnore(true);

$this->addElements(array(
$name,
$pname,
$address,
$contact,
$hobbies,
$id,
$addentry
));
}
}
?>
———————————————–
also we have to create an addAction in IndexController to make the data entry work, updates version of IndexController.php is following, please make corresponding changes.
———————————————–
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$form = new SortForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$sortData = $this->_request->getPost();

}
if((empty($sortData[‘search’])==0)){

if(isset($sortData[‘sortby’]) && isset($sortData[‘sorttype’]))
{

$data=$users->fetchAll($users->select()->order($sortData[‘sortby’].” “.$sortData[‘sorttype’])->where(‘name = ?’, $sortData[‘search’]));
}
else
{

$data=$users->fetchAll($users->select()->where(‘name = ?’, $sortData[‘search’]));
}

}

elseif(isset($sortData[‘sortby’]) && isset($sortData[‘sorttype’])){

$data=$users->fetchAll($users->select()->order($sortData[‘sortby’].” “.$sortData[‘sorttype’]));
}

else {

$data = $users->fetchAll($users->select());

}

$this->view->data = $data;
}

//add action

public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;

if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
unset($formData[‘addentry’]);
$users->insert($formData);
echo “Data Successfully stored”;
}
}
}

}
?>
———————————————–
The only thing left is, create add.phtml file in project/application/views/scripts/index/ and write the following code in it.

———————————————–
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php

echo $this->form;
?>
———————————————–
Now we are done with all the coding. You must try running your application now at
Viewing the Entries :http://localhost/project/index
Adding Entries :http://localhost/project/index/add
While looking at the links you me seem that how http://localhost/project/index/add will run, you have created to add/ Directory inside the index/ Directory, then I must tell you that, It is the Magic of Rewrite_mod.
Try running your application, if your face any error, just make sure following things are right again ->
1) Rewrite_mod is enabled
2) your directories and files are readable to you.
3) Re-check the braces, most of the times Errors are with the braces.
4) check your configuration paths in index.php.
5) Also, Try refilling your cup of coffee.

Being Lazy ? huh ? Download the Source
I hope I have not missed something.
Good Luck.

System.out.print(“Vigas Deep”);


Comments

5 responses to “Zend Framework – First Database Driven Application – Tutorial”

  1. sukhdeep Avatar
    sukhdeep

    great work bongo..

  2. hey vigas… u have given us the name of site from where we have to download the zend framework…. after cliking on that link wht we have to dooo and…… after downloading the file where it should be placed in the directories and wht is the meaning off these lines….. “Then Extract the Library folder inside the archive to our project/ directory, graphically or use following commands (for UBUNTU)
    Log in to root and extract -> “……………… help me out…..pls

  3. hey vigas pls help me out dont know how to download zend framework and where to store it

  4. Hello Navneet,
    You’ve to download the Zend Framework 1.11.11 Minimal which is a tar.gz, extract the tar.gz with given command or directly by right clicking > extract all. When you will extract it, you will find a library folder inside that and you have to place it under /project folder, In which all your other files regarding to the application are placed.
    Thank you for your interest in tutorial.
    Good Luck.

  5. Really good start thanks for tutorials

Leave a Reply

%d bloggers like this: