Hello,
I have experience in codeigniter, and in it just set the settings in database.php and you connect to the database. In zend, I have no idea.
Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDB() {
$dbConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/db.ini');
$dbAdapter = Zend_Db::factory($dbConfig->adapter, array(
'host' => $dbConfig->hostname,
'username' => $dbConfig->username,
'password' => $dbConfig->password,
'dbname' => $dbConfig->dbname
));
My_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
Zend_Registry::set('db', $dbAdapter);
if (APPLICATION_ENV == 'development') {
$profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
$profiler->setEnabled(true);
$dbAdapter->setProfiler($profiler);
}
}
public function _initRouter()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
}
}
<?php
class Application_Model_MBT extends Zend_Db_Table_Abstract
{
/**
Inserts city if does not exist (assuming all city names are unique)
*/
private function get_city_id($city_name)
{
$stmt = $db->query(
'SELECT id FROM cities WHERE city = ? LIMIT 1',
array($city_name)
);
$rows = $stmt->fetchAll();
return $rows;
}
public function insert_city($city_name)
{
$city = $this->get_city_id($city_name);
if (empty($city))
{
$stmt = $db->query(
'INSERT INTO cities (id, city) VALUES (DEFAULT, ?)',
array($city_name)
);
//has to be some function for last insert id, but this will be ok as well
$city = $this->get_city_id($city_name);
//inserted so must be one row
$city_id = $city[0]['id'];
}
else {
$city_id = $city[0]['id'];
}
return $city_id;
}
/* if not exists */
public function insert_team($id, $cities_id, $name, $web_page)
{
$team = $this->get_team($id);
if (empty($team)) {
$stmt = $db->query(
'INSERT INTO teams (id, cities_id, name, web_page) VALUES (?, ?, ?, ?)',
array($id, $cities_id, $name, $web_page)
);
}
}
private function get_team($id)
{
$stmt = $db->query(
'SELECT id FROM teams WHERE id = ? LIMIT 1',
array($id)
);
$rows = $stmt->fetchAll();
return $rows;
}
public function insert_player()
{
//TODO:
}
}
Here is the model code, but it does not know what is $db. I cant even create a constructor in model, I am getting errors. In the contructor I was placing
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
but even blank constructor thorws errros:
function __construct() {
}
In contrucktor its wrong to connect to database, it should be somewhere more general. But I cannot find a normal tutorial for this.