这可以在 Zend Framework 中以几种方式重写。这是我通常使用Zend_Db_Table_Select 编写选择的方式。
<?php
// For brevity, $dbTable = a Zend_Db_Table object
// first construct the subquery/join for the IN clause
// SELECT idGameType FROM GameType HERE nameGameType = 'Xbox'
$subselect = $dbTable->select()
->from('GameType', array('idGameType'))
->where('nameGameType = ?', 'Xbox'); // quotes Xbox appropriately, prevents SQL injection and errors
// construct the primary select
// SELECT titleGame FROM Game WHERE idGameType IN (subquery)
$select = $dbTable->select()
->setIntegrityCheck(false) // allows us to select from another table
->from($dbTable, array('titleGame'))
->where('idGameType IN (?)', $subselect);
$results = $select->query()->fetchAll(); // will throw an exception if the query fails
if(0 === count($results)) {
echo "No Results";
}else{
foreach($results as $result){
echo $result['titleGame'] . '<br />';
}
}
您也可以将 SQL 编写为字符串,但在可能的情况下,面向对象的方法是理想的,因为它使查询更具可移植性,最重要的是可以很容易地保护您的查询。
例子:
$db = Zend_Db_Table::getDefaultAdapter(); // get the default Db connection
$db->select("select * from table where id = 3"); // doable, but not recommended
您还可以创建一个prepared statement 到Zend_Db_Statement 到PHP 的PDO 扩展。
$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->execute(array('goofy', 'FIXED'));
第一种方法,面向对象的流畅界面是您看到最多的方法,也是我推荐开始使用和使用的方法。
通读Zend_Db Manual Pages,尤其是Zend_Db_Table_Select、Zend_Db_Table 和Zend_Db_Adapter,了解更多信息。即使是快速阅读 ZF Quickstart 并特别注意 Db 部分也是有帮助的。它将展示如何将表类设置为应用程序和数据库之间的网关。