note 84820 added to function.rand

From: Date: Thu, 31 Jul 2008 15:46:25 +0000
Subject: note 84820 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-142974@lists.php.net to get a copy of this message
You don't need fancy queries to grab a random row(s) from MySQL; it's actually quite simple. In fact, you can do it in a single query. <?php $random_rows = array(); $query = mysql_query("SELECT * FROM tablename ORDER BY RAND() LIMIT 1"); while($row = mysql_fetch_array($query)) { $random_rows[] = $row; } ?> You can extend LIMIT to any number, so you can select 10 random rows. Also, because it uses ORDER BY the rows are always unique if you select 10 rows, for example. This might work on other database systems such as MsSQL and PostgreSQL but I haven't tested them. ---- Server IP: 92.48.74.199 Probable Submitter: 78.149.157.215 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/84820 Del: integrated -- https://master.php.net/note/delete/84820/integrated Del: useless -- https://master.php.net/note/delete/84820/useless Del: bad code -- https://master.php.net/note/delete/84820/bad+code Del: spam -- https://master.php.net/note/delete/84820/spam Del: non-english -- https://master.php.net/note/delete/84820/non-english Del: in docs -- https://master.php.net/note/delete/84820/in+docs Del: other reasons-- https://master.php.net/note/delete/84820 Reject -- https://master.php.net/note/reject/84820 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#142974) next »