2012-02-27 140 views
0

我花了2个小时只是选择语句。zend select字符串语句

我在做什么错?

public function fetchSpecific($moderatorid = 1) 
    { 

     $resultSet = $this->getDbTable()->fetchAll("moderatorid = ".$moderatorid); 

     $entries = array(); 
     foreach ($resultSet as $row) { 
      $entry = new Application_Model_Network(); 
      $entry->setId($row->id) 
        ->setName($row->name) 
        ->setModeratorId($row->moderatorid); 
      $entries[] = $entry; 
     } 
     return $entries; 
    } 

这是所有关于这一行:

$resultSet = $this->getDbTable()->fetchAll("moderatorid = ".$moderatorid); 

它给我一个错误喜欢这样的:

Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 

回答

2

技术上是语法应该工作,虽然我会推荐改变它了以确保您的数据正确转义。当你遇到这个错误时,你看到$moderatorid有什么价值?我怀疑这个变量出于某种原因正在生成语法错误。

试试这个:

$results = $this->getDbTable() 
       ->fetchAll($this->getDbTable() 
           ->getAdapter() 
           ->quoteInto('moderatorid = ?', $moderatorid)); 

这将确保$moderatorid被正确地转义,应有助于防止语法错误,甚至更重要的是它可以防止可能的SQL注入。

使用Zend_Db_Table::fetchAll()时遇到的另一个问题是,当遇到类似的错误时,很难调试正在执行的查询。

为了解决这个问题,自己构建SELECT语句,以便您可以在需要调试正在执行的实际SQL时回显该值。

$select = 
$this->getDbTable() 
    ->select() 
    ->from($this->getDbTable()) // optionally you can specify cols as the 2nd param 
    ->where('moderatorid = ?', $moderatorid); 

echo $select; // e.g. SELECT `table`.* FROM `table` WHERE (moderatorid = 1) 

$results = $this->getDbTable()->fetchAll($select); 

希望能帮助你解决你的问题。

一些有用的参考文献:
Zend_Db_Select
Zend_Db_Table

+0

尼斯解释。 +1 – RockyFord 2012-02-28 04:59:30

+0

这救了我的生命.. – Proto 2012-02-28 07:51:52

+0

非常好,很高兴帮助! – drew010 2012-02-28 08:06:15