J.Doe J.Doe - 1 month ago 7
PHP Question

MySql ORDER By rand() one row

I have got this php code

$coma_count=substr_count($Hob,',');
if ($coma_count==0) {
$query="SELECT * FROM user_opt WHERE Interests='$Hob' LIMIT 80";
}else{
$expl=explode(',',$Hob);
for ($i=0; $i <=$coma_count; $i++) {
$query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";
}
}
$sql=$con->query($query." ORDER BY RAND()") or die($con->error);


Number of
$coma_count
varies from 0 to 112 and the problem is when
$coma_count
is 0 (means only country was selected) my query is going to look like this
SELECT * FROM user_opt WHERE Country='$Countr' LIMIT 80 ORDER BY RAND()
which is not accepted by SQL.What can i do?

Answer

Create a $limit variable, set it if need be, then append it:

$limit = '';
$coma_count=substr_count($Hob,',');
    if ($coma_count==0) {
        $query="SELECT * FROM user_opt WHERE Interests='$Hob'";
        $limit = " LIMIT 80";
    }else{
        $expl=explode(',',$Hob);
        for ($i=0; $i <=$coma_count; $i++) { 
                $query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";      
        }
}
$sql=$con->query($query." ORDER BY RAND()".$limit) or die($con->error);