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 (10)
- Domains (1)
- Freeware (1)
- Graphics (1)
- Life (1)
- Open Source (2)
- Servage (1)
- SMS (1)
- Software (3)
- Ubuntu (2)
- WAMP (2)
- Web Development (13)
- Windows (2)
- Work (2)
Feed
The articles RSS feed is available.
Elsewhom
-
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. -
Hackszine.com.
Hack the way you think -
GNOME Coder.
Modern open source software development -
@TheKeyBoard.
Be a developer, not a typist!
Chris Hartjes' blog on CakePHP, life and more

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 on 2/10/08:
thanks. i thought i have to use like this rand(Profile.id) to get random record. a simple rand() works.Bharat wrote on 20/5/09:
Yes that wotked perfectly.. Thnks Dear