We often need to get a random row from MySQL(as an example) table .
But using ORDER BY RAND is not (eventually very not) the best practice. There're much better ways,
found in a very good article.
And this is my example function (written for one CMS)
function randomID($typeCode, $groupID=0)
{
global $DB;
$res = 0;
$where ='1';
$from = '';
if($typeCode == 'vote')
{
$from = "b_vote";
$where = "CHANNEL_ID=1 AND ACTIVE='Y'";
}
else return false;
$dbRes = $DB->Query("SELECT MAX(ID) as M FROM $from ");
if($maxID = $dbRes->Fetch())
{
$x = rand(0,$maxID['M']);
$dbRes = $DB->Query("SELECT ID FROM $from WHERE ID>=$x AND $where");
if($dbRow = $dbRes->Fetch()) return $dbRow['ID'];
}
return $res;
}
But using ORDER BY RAND is not (eventually very not) the best practice. There're much better ways,
found in a very good article.
And this is my example function (written for one CMS)
function randomID($typeCode, $groupID=0)
{
global $DB;
$res = 0;
$where ='1';
$from = '';
if($typeCode == 'vote')
{
$from = "b_vote";
$where = "CHANNEL_ID=1 AND ACTIVE='Y'";
}
else return false;
$dbRes = $DB->Query("SELECT MAX(ID) as M FROM $from ");
if($maxID = $dbRes->Fetch())
{
$x = rand(0,$maxID['M']);
$dbRes = $DB->Query("SELECT ID FROM $from WHERE ID>=$x AND $where");
if($dbRow = $dbRes->Fetch()) return $dbRow['ID'];
}
return $res;
}