Re: Randomly select 5 records from a db

From: Date: Mon, 02 Oct 2000 23:17:54 +0000
Subject: Re: Randomly select 5 records from a db
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-18326@lists.php.net to get a copy of this message
At 5:11 PM -0500 10-02-2000, Ben Weinberger wrote:
Hi~ I am constructing part of a PHP4 page that I would like to randomly select 5 records from my MySQL db and display them. I know how to do the standard selects and display the data, but nothing random. The database lists benefits of being a member of our association, and we would like to display different ones each time the query is performed-- is there a way to randomly query the db for 5 records? I tried using the following but it didn't work.... $sql= "SELECT * from meminfo where type='bene'"; $result= mysql_query($sql); while ($myrow= mysql_fetch_array($result)) { $benefits=$myrow["title"]; print "$benefits<BR>"; //this is just to test to make sure it's pulling the data I want srand ((double) microtime() * 10000000); $input = array ("$benefits", 5); $rand_keys = array_rand ($input); print $input[$rand_keys[0]]."\n"; print $input[$rand_keys[2]]."\n"; print $input[$rand_keys[3]]."\n"; print $input[$rand_keys[4]]."\n"; print $input[$rand_keys[5]]."\n"; }
If you're using MySQL 3.23 or higher you can just use: SELECT * FROM meminfo ORDER BY RAND() LIMIT 5 -- Paul DuBois, paul@snake.net

« previous php.general (#18326) next »