简体   繁体   English

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

[英]Pulling random data from table and then displaying it

I want to pull 1 random ID from a table and display the "text1" and the "text2" when they click a button. 我想从表中提取1个随机ID,并在单击按钮时显示“ text1”和“ text2”。 This is my current code, it does not have the button because I didn't find any help on google. 这是我当前的代码,它没有按钮,因为我在google上找不到任何帮助。

<?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"];
                                     }

?>">

Note that I have this code already at the top of the page in use for other things 请注意,此代码已经在页面顶部,可用于其他用途

<?php
session_start();
include 'config.php';

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

Inside the config.php it has all of the MySQL login/database info. 在config.php中,它具有所有MySQL登录/数据库信息。

Firstly this makes no sense and it not doing anything as it is now.. 首先,这没有任何意义,并且它不像现在那样做任何事情。

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

Take that out, im amazed you're not getting php errors when you try to run.. ? 拿出来,我很惊讶您在尝试运行时没有遇到php错误。

In order to do this you want to structure your array first so you can pull out your random item from it. 为了做到这一点,您想先构造数组,以便从中取出随机项。

$arrayOfResults = $result->fetch_assoc();

Now we select a random item 现在我们选择一个随机项目

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

and viola echo $randomItem; 中提琴echo $randomItem; you should have what you're looking for. 您应该拥有想要的东西。

the filler code ill leave to you! 填充代码不正确!

As per your comments, your $random item will probably have keys.. so you can echo it as so : $randomItem['name'] or $randomItem['id'] where the KEY is your column ID in the database.. 根据您的评论,您的$ random项可能会有键..因此,您可以这样回显它: $randomItem['name']$randomItem['id']其中KEY是数据库中的列ID。

References : 参考文献:

Array_Rand Array_Rand

Fetch-assoc return details 提取关联返回详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM