note 7730 added to rand
| From: | whoisthisfreak at bigfoot dot com | Date: | Sat, 12 Aug 2000 18:39:13 +0000 |
| Subject: | note 7730 added to rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-1496@lists.php.net to get a copy of this message | ||
I have found a better and more reliable way of getting a random record from an sql database with
php. Methods that I had found on the Internet forced you to linearly cycle through records until you
reached a suitably random one. Other methods required you to have a consecutively numbered index
field in the table. Although most tables DO have numerical indexes, sometimes the numbers are not
consecutive. This is what I came up with:
function randomrec($table, &$row, $db)
{
$sql = "SELECT * FROM $table";
$result = mysql_query($sql, $db);
$numrecs = mysql_num_rows($result);
srand((double)microtime()*1000000);
$recnum = rand(0, $numrecs-1);
$sql = "SELECT * FROM $table LIMIT $recnum, 1";
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
http://www.php.net/manual/function.rand.php