PHP Zend Framework – How to Fetch and Display Last 4 Table Rows

arraymodelmodulePHPzend-framework

The following code currently outputs the first row matching the criteria is_read != 1', 'is_remove != 1'. I need to modify this code to output the last 4 table rows that matches said criteria. I tried a few things but none worked.

This current code displays the latest notification at the top of the admin page. i want it to display the last 4 notification, one after the other.

Please Help!

ModuleName/Model/Resource/

public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
    $adapter = $this->_getReadAdapter();
    $select = $adapter->select()
        ->from($this->getMainTable())
        ->order($this->getIdFieldName() . ' DESC')
        ->where('is_read != 1')
        ->where('is_remove != 1')
        ->limit(1);
    $data = $adapter->fetchRow($select);

    if ($data) {
        $object->setData($data);
    }

    $this->_afterLoad($object);

    return $this;
}

Here are some other codes that are used…

ModuleName/Model/

 public function loadLatestNotice()
{
    $this->setData(array());
    $this->getResource()->loadLatestNotice($this);
    return $this;
}

ModuleName/Block/

public function getLatestNotice()
{
    return  $this->_getHelper()
        ->getLatestNotice()->getTitle();
}

Template/

<div class="notemssg" >
        <p id="notetitle" href="<?php echo $latestNoticeUrl ?>" onclick="this.target='_blank';"><?php echo $this->getLatestNotice() ?></p>
        <p id="notedate"><?php echo $this->getLatestNoticeDate() ?></p>
    </div>

ive tried changing the limited to 4, but i didnt see any changes. I've also tried using fetchall instead of fetchrow, which didnt show anything. I;m starting to wonder, do i need to do a array echo in the template code to display it?

Best Answer

in sql limit will display the number of rows you want to fatch. you can get 4 rows by limit it to 4 ->limit(4);

->order($this->getIdFieldName() . ' DESC') will display the and get the table rows in descending order so you can get last record first and than limit it to 4 will get latest 4 notifications in admin.

use $data = $adapter->fetchAll($select); instead of $data = $adapter->fetchRow($select);

this works for me i hope this also works for you buddy.

please clear cache after editing.

public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
    $adapter = $this->_getReadAdapter();
    $select = $adapter->select()
        ->from($this->getMainTable())
        ->order($this->getIdFieldName() . ' DESC')
        ->where('is_read != 1')
        ->where('is_remove != 1')
        ->limit(4);
    $data = $adapter->fetchAll($select);
    echo "<pre>";
    print_r($data);
    if ($data) {
        $object->setData($data);
    }

    $this->_afterLoad($object);

    return $this;
}

I hope this will help you.

Related Topic