Zend framework MySQL query random records

  • SumoMe

Hello, sometimes we need a query which will return random rows from table. In your model create this:

    public static function getRandom()
    {
        $model = new self();
        return $model->fetchAll($model->select()
            ->order('RAND()')
            ->limit(8)
            ->from($model)
        );
    }

This will return 8 random rows from the table.
The problem with RAND() function is performing slowly. It needs to assign a random id to each row in database table and find a Unique row. For a small amount of rows will be OK to use RAND() function.
And this work only for MySQL.

That’s all for me. Good luck.

Posted in MySQL, Php, Zend Framework by Niko at March 28th, 2012.
Tags: , , , , ,

Leave a Reply

*