开发者

Novice: How to properly set up db connection on zend framework?

I'm pretty new to OOP and Zend. So far I'm trying to set up a db connection. I have this in my application.ini file:

resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "dbtest"
resources.db.isDefaultTableAdapter = true

Supposedly I can access the db adapter everywhere with开发者_C百科:

$db = Zend_Db_Table::getDefaultAdapter();

The problem is most guides assume you automatically know where to place that, but I honestly have no idea. What I'm doing so far is in my Index.php model I have a method:

public function getPosts()
{
 $db = Zend_Db_Table::getDefaultAdapter();
 $sql = "SELECT * FROM posts";
 $result = $db->fetchAll($sql);
 return $result;
}

With that one query it would be okay, but if I want to create more methods that hold my other queries each time I will have to call $db = Zend_Db_Table::getDefaultAdapter() so I'm sure I'm not doing this in an efficient way. I've already tried placing it in various __construct() and init() methods, but it wouldn't work. Where would I add the code without having to call it each time? Thanks.


An easy way to run your queries would be to create a class for each of your tables that extends Zend_Db_Table_Abstract which would provide you some handy methods to help you get your stuff from your database.

While using this method you will be able to call your table content through

$postsTable = new Model_Db_Tables_Posts() // Assuming you put your class post in the folders models/db/tables/
$posts = $postsTable->fetchAll();

for a more specific post you could also fetch it by id using

$singlePost = $postsTable->find(1); // Assuming the id of the post you want is 1

And then for creating new entries you could go with

$data = array('title' => 'Some title', 'content' => 'Some Content') // where the key is the table field and the value is the value you want to insert
$newId = $postsTable->insert($data);

And for updating

$data = array('title' => 'Some title', 'content' => 'Some Content')
$db = $postsTable->getAdapter();
$where = $db->quoteInto('id = ?', $id); // quoteInto is used to escape unwanted chars in your query, not really usefull for integers, but still a good habit to have
$postsTable->update($data, $where);

Hope this helps you a bit, you could find more info in the official ZF doc at http://framework.zend.com/manual/fr/zend.db.table.html and http://framework.zend.com/manual/fr/zend.db.table.row.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜