Re: Randomly select 5 records from a db

From: Date: Mon, 02 Oct 2000 23:59:32 +0000
Subject: Re: Randomly select 5 records from a db
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-18329@lists.php.net to get a copy of this message
At 6:53 PM -0500 10-02-2000, Ben Weinberger wrote:
It doesn't look like that wants to work... unless I'm doing something wrong-- here's my new script... <? // connect to database here $sql = "SELECT * FROM meminfo WHERE type='bene' ORDER BY RAND()"; $result= mysql_query($sql); while($myrow=mysql_fetch_array($result)) { print "$myrow[title]<BR>"; } mysql_close($db); ?> It says "Warning: Supplied argument is not a valid MySQL result resource... on line 9" Line 9 is "while($myrow=mysql_fetch_array($result)) {>while($myrow=mysql_fetch_array($result)) {". Any ideas?
Put this after the mysql_query() call. Perhaps you have MySQL 3.22, which requires a different method. if (!$result) print (mysql_error()); If that prints an error, try this query instead, where 'x' is some numeric column in your table: SELECT *, x*0+RAND() AS rand_col FROM meminfo WHERE type='bene' ORDER BY rand_col LIMIT 5
Thanks, -Ben At 06:17 PM 10/2/2000 -0500, Paul DuBois wrote:
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
-- Paul DuBois, paul@snake.net

« previous php.general (#18329) next »