Extract random MySQL records in PHP

More tags

Extract random MySQL records in PHP
To extract a random record from f.e. a MySQL table you can use this sample PHP code to get you going. The snippet uses rand() to generate a random number and LIMIT to select the record from the SQL table.
Author: SimplytheBest Inc Price: Free GPLv2 Type: PHP,MySQL

To extract a random record from a MySQL table you can use the following sample PHP code.

Solution 1

<?
// define your query

$your_query = "SELECT * FROM yourtable WHERE active = 'yes' AND (A > 0 OR B > 0) AND (abc LIKE '%$xyz%' OR abc LIKE 'all%') AND whatever = 'yes' ORDER BY rand() LIMIT ".$whatever." ";
$query = @mysql_query($your_query );
$count = mysql_fetch_array($query);
if ($count)
{

whatever you intend to do

}
?>

Solution 2

<?
// define your query

$your_query = "SELECT * FROM yourtable WHERE match1=\'yes\' AND match2<>\'yes\' AND ondate >=".date("Ymd")."";

// count the number of rows returned that match the query

$rowcnt = mysql_num_rows(mysql_query($your_query));

// generate a random number between 0 and the number of rows found (always -1)

$randvar = rand (0,$rowcnt-1);

// get the random record (in this case 1) by using the LIMIT statement which uses the record number generated in $randvar

$your_result = mysql_fetch_array(mysql_query("SELECT * FROM yourtable WHERE match1=\'yes\' AND match2<>\'yes\' AND date >=".date("Ymd")." LIMIT  ".$randvar.", 1"));

if ($your_result) {   // check if there is a result

if so, here comes whatever you intend to do with the random record,

echo $your_result["field"];
}
?>

Hope this makes you happy enough to link to us! =:)