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:
$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_Abstractwhich 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
for a more specific post you could also fetch it by id using
And then for creating new entries you could go with
And for updating
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