简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM