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.
- // This statement queries a Testimonial model for one random entry.
- $this->Testimonial->findAll(null,null,'rand()',1,null,null);
Comments
Leave a Comment
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
-
Cool Hunting.
Finding things in the intersection of design, culture and technology that excite the imagination and inspire creativity -
The Tech.
MIT's Student Newspaper -
Jeffrey Zeldman Presents the Daily Report.
Web design, news and info since 1995 -
cakebaker.
Baking cakes with CakePHP
Enlightening CakePHP articles

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 :)
richard wrote 1 week, 6 days ago:
thanks. i thought i have to use like this rand(Profile.id) to get random record. a simple rand() works.