ZF Data Insert in DB

Ads

To do database related tasks we need to create a model class and it is not previously built (like other classes) by the Zend Framework. The model class contains the name of the table and it contains all the database related tasks in the form of functions...

How to insert values in a table in Zend Framework:

It is a very common phenomenon in web site development that we need to take
values from user and insert in a table. Suppose you have done this activity
before in common php programming, in Zend Framework it is slightly tedious job,
but when you will get used to it, you can perform insert, update or any other
activity with so much ease.

So, let's get started:

To do database related tasks we need to create a model class and it is not
previously built (like other classes) by the Zend Framework. The model class
contains the name of the table and it contains all the database related tasks in
the form of functions. To know in details please visit the previous page of this
tutorial.

Now to insert values in the table we will create a function called addBooks()
in the Class named Application_Model_DbTable_Books which extends
Zend_Db_Table_Abstract, the coding of the function is as follows:

public function

addBooks($name,$publisher,$title)

{

$data=array("name"=>$name,"publisher"=>$publisher,"title"=>$title);

$this->insert($data);

}

Create an action for adding books as follows:

zf create action add Index

in the command prompt, it will create an addAction method in the
IndexController.php file.

Now we will make some necessary changes IndexController.php file as follows:

public function addAction()

{

$this->view->title="Add
New Book ";

$this->view->headTitle("Add
Page");

$request=$this->getRequest();

$form=new
Application_Form_Login();

$this->view->form=$form;

if($request->isPost()){

if($form->isValid($request->getPost())){

$author=$form->getValue('author');

$publisher=$form->getValue('publisher');

$title=$form->getValue('title');

$books=new
Application_Model_DbTable_Books();

$books->addBook($author,$publisher,$title);

$this->_helper->redirector('index');

}

}

}

Output will be as follows:

Now we can add new book from the above UI, and the data will be directly
inserted in the database.