note 7730 deleted from rand by hholzgra
| From: | hholzgra@php.net | Date: | Fri, 25 Aug 2000 10:40:33 +0000 |
| Subject: | note 7730 deleted from rand by hholzgra | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-3232@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);
}