我没有得到正确的随机值我的数据库中有6个值我给限制3但前4项是随机的

33qvvth1  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(251)

我需要6个人的3个问题。但每次随机显示快4题。

/*for random question*/
public function qustionShow($question){

    $query = $this->conn->query("select * from question where cat_id='$question'");
    $c = mysqli_num_rows($query);
    $rand = rand(3, $c)-3;

    $show = $this->conn->query("select * from question where cat_id ='$question' and id >'$rand' LIMIT 3");
    while ($row=$show->fetch_array(MYSQLI_ASSOC)){
        $this->qus[]=$row;
    }
    return $this->qus;  
}
06odsfpq

06odsfpq1#

您可以使用order by rand()减少和优化代码。
尝试以下操作:

public function qustionShow($question, $limit=3){
    $show = $this->conn->query("select * from question where cat_id ='$question' ORDER BY RAND() LIMIT $limit");
    while ($row=$show->fetch_array(MYSQLI_ASSOC)){
        $this->qus[]=$row;
    }
    return $this->qus;  
}

相关问题