Skip to content

Instantly share code, notes, and snippets.

@smonteverdi
Created March 7, 2012 15:52
Show Gist options
  • Save smonteverdi/1993920 to your computer and use it in GitHub Desktop.
Save smonteverdi/1993920 to your computer and use it in GitHub Desktop.
PHP: Generate Random Record
<?
// 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"];
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment