You Are Here: Home » Articles » Fetch a Random Database Entry with CakePHP

Fetch a Random Database Entry with CakePHP

CakePHP's findAll() function can be used to fetch one or more random entries from a database.

Tagged with CakePHP and Web Development
Posted on 27/11/06 by Paul Herron

To achieve this, all we need to do is order our retrieved records randomly. We can do that by inserting the rand() function in the $order field.

To take only a certain number of these randomised entries, we can use the $limit parameter. This is set to 1 in the example below.

  1. // This statement queries a Testimonial model for one random entry.
  2. $this->Testimonial->findAll(null,null,'rand()',1,null,null);

Comments

AD7six wrote on 16/7/07:

You'll get headaches doing that with a none-trivial sized table ;), order by rand is the best way to tie up the db calculating random numbers.

Better to return a random result from an ordered resultset. In words:

* get the number of rows (a findCount)

* select a random number between 1 and the max

* find page (random) showing 1 result per 'page'

Cheers,

AD

Ps. I agree with everyone regarding the site design :) 

Leave a Comment

*
*
*

« Back to Articles

Article Tags

Show all articles, or just those tagged as:

Apache (1)
CakePHP (5)
Domains (1)
Ethics and That (1)
Freeware (1)
Open Source (1)
Servage (1)
SMS (1)
Software (1)
WAMP (1)
Web Development (6)
Windows (2)

Feed

The articles RSS feed is available here.

Elsewhom

  • Never Knowingly Underwhelmed.
    Andrew Collins is a journalist, scriptwriter and broadcaster
  • If Then Else.
    A weblog by Eduardo Sousa, a film and video geek from Porto, Portugal, with a knack for design and a keen interest in the affairs of mankind
  • Modern Life.
    A blog about the web - development, design, search engines and statistics. Sometimes controversial, occasionally satirical and usually on the nose.
  • cakebaker.
    Baking cakes with CakePHP
    Enlightening CakePHP articles

See More…

Back to top.