SlowlyDeath
SlowlyDeath

Reputation: 1

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?

Upvotes: 0

Views: 299

Answers (4)

olimortimer
olimortimer

Reputation: 1373

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

}

Upvotes: 0

Liam Allan
Liam Allan

Reputation: 1115

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

Upvotes: 1

heinkasner
heinkasner

Reputation: 425

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.

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33542

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

?>

Upvotes: 0

Related Questions