首页 > 解决方案 > 我没有得到正确的随机值。我的数据库中有 6 个值。我给限制 3。但前 4 项显示随机

问题描述

我需要 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;  
}

标签: phpmysqlsqlweb

解决方案


您可以使用 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;  
}

推荐阅读