Zend Framework 中的 Zend_Db 可以針對資料庫操作,而 Zend_DB_Table 底下繼承了許多像 Zend_Db_Select 之類的物件提供一些函式幫你組合 SQL query 和存取 DB
範例
1.產生 DB Adapter
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'johnson',
'password' => '123',
'dbname' => 'test'
));
// OR
// 設定檔寫在 application/configs/application.ini
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
// OR
// 直接 Extend Zend_Db_Table_Abstract 的自訂 DB Adapter
2.組合 Query String
$select = $dbAdapter->select()
->from('record', '*')
->joinLeft('class', 'class.class_id = record.class_id')
->where('record.dep_id = ?', 1)
->where('record.date = ?', time())
->order(array('record.class_id DESC', 'record.dep_id'))
->limit(1, 1);
// 如果需要 debug 可以直接輸出成字串
echo $select->__toString();
// 根據步驟1,使用的物件不同權限會有些不一樣(直接繼承 Zend_Db_Table_Abstract 的話,因為 Zend_Db_Table_Row 只能操作一張表)
// 如果在使用 join 時遇到 Select query cannot join with another table,要關閉setIntegrityCheck
$select->setIntegrityCheck(false);
3.執行 Query String
$result = $dbAdapter->fetchAll($select);