Insert and Fetch the data in Zend Framework

Today i am working on Zend Framework and learn how to data is inserted and fetched from database. Follow these simple steps for this purpose.

First create your project with this command

zf create project hello

Now do  some database setting in application.ini file, Settings is

resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = database username
resources.db.params.password = database password
resources.db.params.dbname = database name
resources.db.isDefaultTableAdapter = true

Now do some coding for controller

<?php
require_once(dirname(__FILE__).'/../models/user.php');
class IndexController extends Zend_Controller_Action
{

public function init()
{
}

public function indexAction()
{
$etc=new Albums();                                                                               //model class
$etc->albums=$etc->get_data();                                            //model class function
$this->view->albums=$etc;                                   //create data for view

//if you want to fetch all data from table then enable this code

/*

$etc->albums=$etc->fetchAll();

$this->view->albums=$etc;

*/

}
}
?>

Now coding for Model

<?php
class Albums extends Zend_Db_Table_Abstract{
protected $_name='etc';                                                   //select table
public function get_data(){
$row = $this->fetchRow('id = ' . '0');                                 //get the data for 0 id
return $row->toArray();

}
}
?>

 

Now coding for view

<?php

//For Fetch all Data

/*foreach($this->albums as $f){
foreach($f as $d){
echo $d->artist."<br>";
echo $d->title;
}
}*/

//For Fetch specific data
foreach($this->albums as $f){
echo $f['title'];
}
?>

 

Now create table in database

CREATE TABLE IF NOT EXISTS `etc` (
`artist` varchar(200) NOT NULL,
`title` varchar(333) NOT NULL,
`id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Now run application on browser.

localhost/appname/public/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s