仅从数据库中选择一次随机条目

问题描述:

I have this code

    $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'];
    }

But every time the page is reloaded I get a different number. How to get a random value only once and that value to remain unchanged as long as I want?

for it to stay forever, you will most probably need to store the winner in a database eg:

$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);
    }

Given that you are selecting a random number, you will in fact get a random number each time it runs.

Nothing to say you can't store it though:

<php
    // file 1

    session_start();
    $_SESSION['winner']=3;

?>

<php
    // file 2 (or reloaded page)

    session_start();
    echo($_SESSION['winner']);

?>

Try using a session object to store the value in the following way:

if(!isset($_SESSION["num"]))
{
    $_SESSION["num"] = $winner;
}

This would set the session if the session has not been set before.

Store the value in the session (or somewhere else), and check to see if it's stored, before checking again;

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'];
    }

}