Search code examples
phpmysqlzend-frameworkzend-db

Why does ? not work in the LIMIT for Zend_Db


I have the following:

public function getAll($limit = 100)
{   
    //if ($thread != 0) { $threadq = "WHERE threadId=$threadId"; }

    $query = <<<EOF
    SELECT 
        x.*
    FROM x

    ORDER BY dater DESC
    LIMIT ?
EOF;
    return self::$db->fetchAll($query, $limit);
}   

It seems it turns the LIMIT x into LIMIT 'x' and so the MySQL query parser goes wrong and complains.

However doing LIMIT $limit works fine

Why does this not work? and is there another method of doing this?


Solution

  • I'm going to go crazy and suggest you keep it easy and use Zend_Db_Select. This appears to be a simple query.

    This demonstration uses a default ZF DbTable as the the adapter (I could just as easily use Zend_Db_Table::getDefaultAdapter();), however it can be adapted to almost any type of query:

    <?php
    
    class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
    {
        protected $_name = 'user';
        protected $_primary = 'id';
    
    public function getAll($limit = 100)
    {
        $select = $this->select();//This is the adapter for this table and implies SELECT * FROM user 
        $select->order('name', 'DESC') //can also pass an array of columns
               ->limit($limit);//limit has a second arg for offset
    
        return $this->fetchAll($select);//returns a rowset object, if an array is required append ->toArray to the fetchall().
    }   
    }