我有这段代码
$query1 = "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `participanti`";
$offset_result = mysqli_query($connect,$query1);
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$query2 = "SELECT * FROM `participanti` LIMIT $offset, 1";
$result = mysqli_query($connect,$query2);
while( $row = mysqli_fetch_assoc($result) ){
$winner = $row['id'];
}
但每次重新加载页面时,我都会得到一个不同的数字。如何只获取一次随机值,并且只要我想要保持该值不变?
答案 0 :(得分:1)
为了让它永远存在,你很可能需要将获胜者存储在数据库中,例如:
$query1 = "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `participanti`";
$offset_result = mysqli_query($connect,$query1);
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$query2 = "SELECT * FROM `participanti` LIMIT $offset, 1";
$result = mysqli_query($connect,$query2);
while( $row = mysqli_fetch_assoc($result) ){
$winner = $row['id'];
$insert = "INSERT INTO `winners`('winner_id') VALUES('".$winner."')";
$save = mysqli_query($connect,$insert);
}
答案 1 :(得分:0)
鉴于您选择了一个随机数,实际上每次运行时都会得到一个随机数。
没有什么可以说你不能存储它:
<php
// file 1
session_start();
$_SESSION['winner']=3;
?>
<php
// file 2 (or reloaded page)
session_start();
echo($_SESSION['winner']);
?>
答案 2 :(得分:0)
尝试使用会话对象以下列方式存储值:
if(!isset($_SESSION["num"]))
{
$_SESSION["num"] = $winner;
}
如果之前未设置会话,则会设置会话。
答案 3 :(得分:0)
将值存储在会话中(或其他位置),并在再次检查之前检查它是否已存储;
if(!isset($_SESSION['winner'])) {
$query1 = "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `participanti`";
$offset_result = mysqli_query($connect,$query1);
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$query2 = "SELECT * FROM `participanti` LIMIT $offset, 1";
$result = mysqli_query($connect,$query2);
while( $row = mysqli_fetch_assoc($result) ){
$_SESSION['winner'] = $winner = $row['id'];
}
}