简体   繁体   中英

Select random entry from database only once

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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