I'm developing a zend application.I have in "config.ini":
resources.db.adapter = "PDO_MYSQL"
resources.db.isDefaultAdapter = true
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "root"
resources.db.para开发者_开发知识库ms.dbname = "test"
To start a connection with my Db and query it what else should I set?
Thanks
Luca
You need to initialize your connection in the bootstrap:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initDatabase(){
// get config from config/application.ini
$config = $this->getOptions();
$db = Zend_Db::factory($config['resources']['db']['adapter'], $config['resources']['db']['params']);
//set default adapter
Zend_Db_Table::setDefaultAdapter($db);
//save Db in registry for later use
Zend_Registry::set("db", $db);
}
}
You don't have to save the connection in the registry.
Create a database model file in your application/models/Data.php
class Model_Data extends Zend_Db_Table_Abstract{
protected $_name='myDatabse'; //the database name
/**
* Create new entry
*
*/
public function create($title,$author,$authorUrl,$category){
$row=$this->createRow();
$row->title=$title;
$row->author=$author;
$row->site=$authorUrl;
$row->category=$category;
$row->save();
return $this->_db->lastInsertId();
}
}
Declare the models in your bootstrap.php
file like so:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initAutoload()
{
$autoLoader=Zend_Loader_Autoloader::getInstance();
$resourceLoader=new Zend_Loader_Autoloader_Resource(array(
'basePath'=>APPLICATION_PATH,
'namespace'=>'',
'resourceTypes'=>array(
'models'=>array(
'path'=>'models/',
'namespace'=>'Model_'
),
)
));
$autoLoader->pushAutoloader($resourceLoader);
}
}
Then make queries via your controller action:
class SearchController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$dataModel=new Model_Data();
$dataModel->create("title","author","url","category");
}
}
精彩评论