从表中提取随机数据,然后显示


Pulling random data from table and then displaying it

我想从表中提取一个随机ID,并在它们单击按钮时显示"text1"answers"text2"。这是我当前的代码,它没有按钮,因为我在谷歌上找不到任何帮助。

<?php select * from TEST order by rand() limit 1 ?>

<label for="exampleInputEmail1">Text1</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Text1" value="
<?php 
while($row = $result->fetch_assoc()) {
echo "" . $row["text1"];
                                     }
?>">

注意,我已经在页面顶部使用了这个代码,用于的其他内容

<?php
session_start();
include 'config.php';
if(!isset($_SESSION['username'])){
header('location:index.php');
exit();
}
?>

在config.php中,它有所有MySQL登录/数据库信息。

首先,这毫无意义,也没有像现在这样做。。

<?php select * from TEST order by rand() limit 1 ?>

去掉这个,我很惊讶你在尝试运行..时没有得到php错误?

为了做到这一点,你想首先构建你的数组,这样你就可以从中取出你的随机物品

$arrayOfResults = $result->fetch_assoc();

现在我们选择一个随机项目

$randomItem = $arrayOfResults[array_rand($arrayOfResults)];

和中提琴echo $randomItem;,你应该有你想要的。

填充代码将留给您!

根据你的评论,你的$random物品可能会有钥匙。。所以您可以这样回显:$randomItem['name']$randomItem['id'],其中KEY是您在数据库中的列ID。。

参考文献:

Array_Rand

获取assoc返回详细信息