在使用Zend_Db的SQL查询中

Fra*_*oss 0 zend-framework zend-db

Zend Framework初学者在这里.我正在尝试获取视频游戏数据库的所有Xbox标题.一张桌子包含游戏.另一个表包含游戏类型(即Xbox,Xbox Live Arcade,......).我通常使用以下查询来获取Xbox标题.

如何使用Zend_Db执行相同的查询?

谢谢,

SELECT titleGame
FROM Game 
WHERE idGameType IN (
    SELECT idGameType 
    FROM GameType 
    WHERE nameGameType = 'Xbox')
Run Code Online (Sandbox Code Playgroud)

dre*_*010 6

这可以通过几种方式在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 />';
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以将SQL编写为字符串,但是在可能的情况下,面向对象的方法是理想的,因为它使查询更具可移植性,最重要的是使查询安全变得非常容易.

例:

$db = Zend_Db_Table::getDefaultAdapter();  // get the default Db connection
$db->select("select * from table where id = 3"); // doable, but not recommended
Run Code Online (Sandbox Code Playgroud)

您还可以通过PHP的PDO扩展创建准备语句.Zend_Db_Statement

$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->execute(array('goofy', 'FIXED'));
Run Code Online (Sandbox Code Playgroud)

第一种方法,面向对象的流畅界面是您将看到的最多,以及我建议开始使用和使用的方法.

通读Zend_Db的手册页和特别Zend_Db_Table_Select,Zend_Db_TableZend_Db_Adapter获取更多信息.即使快速阅读ZF快速入门,特别关注Db部分也很有帮助.它将展示如何将表类设置为应用程序和数据库之间的网关.