Created
October 23, 2010 23:55
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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