0

Seems to be duplicate title, but i accessed all links and none of the pages helped me.

I have the following code:

//Check if form was submitted
if($_POST){
    $number = $_POST['number'];
    $selected_choice = $_POST['choice'];
    $next=$number+1;
    $total=4;

    //Get total number of questions
    $query="SELECT * FROM `questions` LIMIT 4";
    $results = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $total=$results->num_rows;

    //Get correct choice
    $q = "select * from `choices` where question_number = $number and is_correct=1";
    $result = $mysqli->query($q) or die($mysqli->error.__LINE__);
    $row = $result->fetch_assoc();
    $correct_choice=$row['id'];



    //compare answer with result
    if($correct_choice == $selected_choice){
        $_SESSION['score']++;
    }

    if($number == $total){
        header("Location: final.php");
        exit();
    } else {
            header("Location: formular1.php?n=".$next."&score=".$_SESSION['score']);
    }
}

What i need to do, is to get a random number when form is submitted, but that number must be unique and don't repeat until session ends.

I have tried:

$number = range(1, 99);
shuffle($number);

..but i dont know how to integrate that :( Thank you!

7
  • 1
    The general idea about random is that you can get the same value twice, like a dice roll. If you don't want duplicates, the best way is to take a list of numbers, shuffle them, and take one from the list, like taking a card from a shuffled deck. Commented Feb 16, 2019 at 13:15
  • What should be length of random number generated? Commented Feb 16, 2019 at 13:15
  • 1
    @GolezTrol, reading the question I have the impression the OP knows all that. Commented Feb 16, 2019 at 13:16
  • 1
    @trincot I didn't get that at first, but I guess you're right. Nevertheless, I hope the analogy still clarifies the problem for either OP or future readers, and it may help thinking about solutions as well, like "Ok, deck of cards, so I need to keep that somewhere, so I can take one every time. And oh, the deck will run out eventually!" Commented Feb 16, 2019 at 13:20
  • 1
    Then I will prefer to use current time value to have unique generated numbers. Check this link: stackoverflow.com/questions/10640947/…. Commented Feb 16, 2019 at 13:22

1 Answer 1

2

Your idea with a shuffled array is fine, just store it in a session variable:

session_start();
if (!isset($_SESSION["numbers"]) || !count($_SESSION["numbers"])) {
    $_SESSION["numbers"] = range(1, 99);
    shuffle($_SESSION["numbers"]);
}
$next = array_pop($_SESSION["numbers"]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.