Re: Retrieve item from table at random

From: Date: Wed, 07 Feb 2001 04:50:57 +0000
Subject: Re: Retrieve item from table at random
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-38493@lists.php.net to get a copy of this message
"David Robley" <huntsman@hermes.nisu.flinders.edu.au> wrote: > On Wed, 7 Feb 2001 11:28, enthalpy wrote: > > anyone have example code for randomly grabing an item from a mysql table? > > > > Mysql 3.23 will let you order by RAND() and you could use a LIMIT to > restrict to one result. I haven't tried it, though. I can confirm that what David suggested does work. If you're using an older MySQL you can do something like the following. It requires two queries instead of one. First return all records and count # of records (alternate method is to just use an SQL count() statement), then generate a random # in PHP b/w 0 and the # of records, then use an SQL quuery with LIMIT random_row_number, 1 (return 1 record). $result = mysql_query( $sql, $handle ) or die( "No records." ); $result_num_records = mysql_num_records( $result ); srand( ( double ) microtime() * 1000000 ); $row_offset = rand( 0, $result_num_records ); $sql = "SELECT * FROM my_table LIMIT $row_offset, 1 "; -- Steve Werby COO 24-7 Computer Services, LLC Tel: 804.817.2470 http://www.247computing.com/

« previous php.general (#38493) next »