php - 我没有得到正确的随机值。我的数据库中有 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;
}
解决方案
您可以使用 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;
}
推荐阅读
- php - ECS 的 Nginx 给出“未指定输入文件”
- r - 在 R 中绘制伦敦地图上的邮政编码
- grafana - 如何以 json 或任何其他格式访问 Graphite RAW 数据?
- google-polyline - 如何获取折线中所有点的经度和纬度值
- gstreamer - GStreamer 教程 3 无法链接视频板
- python-2.7 - 如何从 .txt 文件中提取数据(时间)?
- javascript - 将鼠标悬停事件传递给下层,同时覆盖具有菜单的 div 元素保持可点击状态
- android - 不能设置外键为空,多个外键
- python-2.7 - 如何检查 Python 字典列表中是否存在键/值?
- z3 - 如何使用 c++ 在 z3 中为现有声明的函数添加新约束?