Re: Retrieve item from table at random

From: Date: Wed, 07 Feb 2001 08:19:51 +0000
Subject: Re: Retrieve item from table at random
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-38507@lists.php.net to get a copy of this message
I've got a better way yet: select RAND() as rand_col, column_name from table_name order by rand_col Only one query for randomized results, no PHP/Perl/etc. You can of course add the 'limit 1' on the end to get one row back. I use this method a lot - my main server is running 3.22.32 but my test server always has the latest version installed, and this way my code is compatible across all versions. Ben At 10:50 PM 2/6/2001, you wrote:
"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/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net For additional commands, e-mail: php-general-help@lists.php.net To contact the list administrators, e-mail: php-list-admin@lists.php.net


« previous php.general (#38507) next »