Search code examples
phprandom

PHP script using random returns the same output every time


I have a PHP script that is supposed to create a MySQL table and fill it with some data.

The column question should be filled with random numbers between 1 and $AutoInc which I define earlier in the code. For some reason I always end up with the same questions:

Question is always 1 2 3 4 5 6 7 8 9 10 11 12

I tried to sleep between the numbers and used rand() and random_int() instead of mt_rand() none of that worked.

PS: I know that $statement3 is terribly coded. For some reason I couldn't get it to work using Questionmarks and an array. I'll change that later so just ignore it.

$usedQuestionsArray = array();
$AutoInc = 12;
for ($x = 0; $x <= 11; $x++) {
    $randomNum = mt_rand(1, $AutoInc);
    while(in_array($randomNum, $usedQuestionsArray)){
        $randomNum = mt_rand(1, $AutoInc);
    }
    array_push($usedQuestionsArray, $randomNum);
    $statement3 = $pdo->prepare("INSERT INTO match" . $ID ." (Question, P" . 
$Player1 . ",P" . $Player2 . ") VALUES (" . $randomNum . ",0,0);");
    $statement3 = $statement3->execute();
}

Solution

  • Found the mistake: Question is PRIMARY_KEY Therefore the Table is sorted accordingly. I set Question to UNIQUE now its working.