DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Zend Framework 1.11 : Storing Data In Mysql Database Using Plain Old SQL
// Data object in application/models/ directory
<?php
/**
* Database handler.
*Name of file Db_Db.php
*/
class Db_Db
{
public static function conn(){
$connParams = array("host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => "test");
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
return $db;
}
}
// Controller in application/controllers/
<?php
/**
*Controller and Actions must be created with the Zend tool
*so that routes are automaticaly updated
*/
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function testConnAction()
{
try{
$connParams = array("host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => "test");
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
}catch(Zend_Db_Exception $e){
echo $e->getMessage();
}
echo "Database object created.";
//Turn off View Rendering.
$this->_helper->viewRenderer->setNoRender();
}
public function testInsertAction()
{
try {
//Create a DB object--> First reference the Db_Db.php model
require_once "/../application/models/Db_Db.php";
$db = Db_Db::conn();
//DDL for initial 3 users
$statement = "INSERT INTO accounts(
username, email, password,status, created_date
)
VALUES(
'test_1', 'test@mail.com', 'password',
'active', NOW()
)";
$statement2 = "INSERT INTO accounts(
username,email,password,status,created_date
)
VALUES(
'test_2', 'test2@mail.com', 'password',
'active', NOW()
)";
$statement3 = "INSERT INTO accounts(
username,email,password,status,created_date
)
VALUES (
?, ?, ?, ?, NOW()
)";
//Insert the above statements into the accounts.
$db->query($statement);
$db->query($statement2);
//Insert the statement using ? flags.
$db->query($statement3, array('test_3', 'test3@mail.com',
'password', 'active'));
//Close Connection
$db->closeConnection();
echo "Completed Inserting";
}catch(Zend_Db_Exception $e){
echo $e->getMessage();
}
//Supress the View.
$this->_helper->viewRenderer->setNoRender();
}
}





