Skip to content

Instantly share code, notes, and snippets.

@TheEmpty
Created October 23, 2010 23:55
Show Gist options
  • Save TheEmpty/642850 to your computer and use it in GitHub Desktop.
Save TheEmpty/642850 to your computer and use it in GitHub Desktop.
This script uses MySQL table standards and will effectively pull multipliable random rows in one query.
function getRandomMySQLRows($table, $rows, $fields = "*"){
// $table = MySQL table
// $rows = number of rows to randomly select
// $fields = fields to select separated by a comma
// returns a string with the SQL that needs to be preformed
if($rows == 0){ return ""; };
$result = mysql_query("SELECT MAX(id) FROM $table WHERE 1");
$count = mysql_result($result,0,0);
$i = 0;
$returns = Array();
while($i <= $rows){
$rand = rand(1,$count);
if($i == 0){
$query_this = "SELECT $fields FROM $table WHERE id > $rand LIMIT 1";
} else {
$query_this .= " UNION SELECT $fields FROM $table WHERE id > $rand LIMIT 1";
}
$i ++;
}
return $query_this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment