Search code examples
phpzend-frameworkzend-dbzend-db-table

Zend framework current method to get single row


i'm new to zend framework, in this simple function i want to get a single 'post' and then i want to find all the comments in the related table

public function getPost($idPost)
{
    $db=  Zend_Registry::get('db');

    $select=$db->select()
            ->from($this->_name, '*')
            ->where("idPost= ".$db->quote($idPost, 'INTEGER'));

    $stmt=$select->query();
    $rowset=$stmt->fetchAll();
    $post=$rowset->current();

    //ora devo aggiungerci i commenti che questo post ha ricevuto
    $comm=$post->findDependentRowset('commenti');

    $ris=array($post, $comm);

    return $ris;

}

in my index controller i i simply call this function, but i get this error:

Call to a member function current() on a non-object in C:\xampp\htdocs\...

where's the mistake?


Solution

  • I think you have a few misconceptions about how you're using Zend_Db.

    1. You're not using the ORM, just the PDO wrapper

    Which means, your queries won't return Zend rowsets and rows and therefore you can't use the methods of you can use on those.

    2. The default fetch mode

    The default fetch mode of the Zend_Db_Statement fetchAll() method is array, if you want it to return an object (stdClass), change the fetch mode before fetching the data:

    $stmt->setFetchMode(Zend_Db::FETCH_OBJ);
    

    3. Using fetchAll() when you actually want one row

    If you just want one row, then don't fetch a whole table! With Zend_Db_Statement, use for example:

    $row = $stmt->fetch();
    

    or

    $rowObj = $stmt->fetchObject();
    

    ... again, that's not a zend row object, just a stdClass instance, but you can do:

    $rowObj->some_field;
    

    on it.

    On the other hand, if this is a method in your Post model, it should look something like:

    public function getPost($idPost)
    {
        return $this->getRow($idPost);
    }
    

    This will return the post, then, if you've setup the table relationships correctly, you can also query for the dependent data or just get all comments with that id separately.