问题
I want to access to database "mysql", I read that we can define the db adapter and db configurations by writing these lines in application.ini file
resources.db.adapter = MYSQLI
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =123456
resources.db.params.dbname = visits_db
I want to get the $db object in order to use in for executing sql statements
$db->insert("inspection_visits_tb",
$insepctionVisitData = array(
'day' => $visit->getDay(),
'date' => $visit->getDate(),
'target' => $visit->getTarget()
));
I want to get it from the application.ini file not like this
require_once 'Zend/Db.php';
$db = Zend_Db::factory("MYSQLI",
array(
"host" => "localhost",
"dbname" => "visits_db",
"username" => "root",
"password" => "123456")
);
because I want to define the db adapter in one place only. What should I do to get the $db object??
回答1:
Set up the db resource in application.ini like you were. Add the isDefaultAdapter option.
resources.db.adapter = "MYSQLI"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "123456"
resources.db.params.dbname = "visits_db"
resources.db.isDefaultAdapter = true
Then to get the $db object...
In Bootstrap.php
protected function _initDb()
{
$this->bootstrap('db');
$db = $this->getResource('db');
Zend_Registry::set('db', $db);
}
From Somewhere else w/out using Registry
$db = Zend_Db_Table::getDefaultAdapter();
Using Zend_Db_Table
$table = new Zend_Db_Table('bugs');
$select = $table->select()...
See also ZF Quickstart, Zend_Db_Table, Zend_Db_Select for more examples.
来源:https://stackoverflow.com/questions/9578891/access-to-database-zend-framework