如何使用MySQL和PHP以随机顺序从数据库中获取值

时间:2016-04-20 06:49:06

标签: php mysql

我需要一个help.i需要在每次调用时使用MySQL和PHP以随机顺序从表中获取值。我正在解释下面的代码。

$subcat_id=$_GET['subcat_id'];
$quad_id=$_GET['quad_id'];
$day_id=$_GET['day_id'];
$data=array();
if(!empty($quad_id) && !empty($day_id)){
$sqlqry=mysqli_query($connect,"select * from db_restaurant_detail where subcat_id='".$subcat_id."' and day_id='".$day_id."'");
if(mysqli_num_rows($sqlqry) > 0){
    while($row=mysqli_fetch_array($sqlqry)){
        $member_id=$row['member_id'];
        $qry="SELECT c.member_id,c.rest_name,c.quadrant,c.city,c.proviance,c.postal,c.address,c.country,c.person,c.mobile,c.url,c.  premium,c.image,c.multiple_image,c.business_phone_no,q.quadrant AS quadrant_name FROM db_restaurant_basic AS c LEFT JOIN db_quadrant AS q ON c.quadrant=q.quad_id WHERE c.member_id='".$member_id."' and c.quadrant='".$quad_id."' and c.status=1";
        $fetchqry=mysqli_query($connect,$qry);
        if(mysqli_num_rows($fetchqry) > 0){
         while($row1=mysqli_fetch_array($fetchqry)){
                      if($row1['multiple_image']==''){
                          $available_image=false;
                      }else{
                           $available_image=true;
                      }
                      $data[]=array("day_id"=>$row['day_id'],"comment"=>$row['comment'],"restaurant_name"=>$row1['rest_name'],"member_id"=>$row1['member_id'],"available_image"=>$available_image,"quadrant"=>$row1['quadrant_name'],"address"=>$row1['address'],"city"=>$row1['city'],"proviance"=>$row1['proviance'],"postal_code"=>$row1['postal'],"country"=>$row1['country'],"person"=>$row1['person'],"mobile"=>$row1['mobile'],"url"=>$row1['url'],"premium"=>$row1['premium'],"image"=>$row1['image'],"business_phone_no"=>$row1['business_phone_no']);
                  }
                  $result=array("data"=>$data,"imagepath"=>$imagepath);
                  }else{
                     $result=array("data"=>$data,"imagepath"=>$imagepath); 
                  }
              }
            }else{
                $result=array("data"=>$data,"imagepath"=>$imagepath);
            }

当用户调用此localhost/spesh/mobileapi/categoryproduct.php?item=1&acn=2&subcat_id=4&quad_id=5时,上面的代码正在执行。当用户每次所需的数据随机而不是asc or desc顺序时,我需要这个URL。请帮助我。

3 个答案:

答案 0 :(得分:3)

使用

ORDER BY rand()

这会产生随机结果。

MySQL Reference

答案 1 :(得分:1)

你可以添加" ORDER BY rand()"在您的查询中。因此它将获取随机数据。

答案 2 :(得分:1)

ORDER BY rand()

它将生成随机结果