3

I don't understand why my code isn't working. The connection works and everything else however when I try to generate a unique random number and check from the MySQL if the number is there it still prints out a random number but it's not UNIQUE. Could anyone help me thx? Here's my code:

$num = rand(1,5);
$sel_query  = "SELECT *  FROM  test"; 
$result2 =  $con->query($sel_query);

$i = 1;
for (;$i<2; $i++)
{
    while($row = mysqli_fetch_array($result2))
    {
        if ($row['id'] == $num) 
        {
             $num = rand(1,5);
             $i = 0; 

        }
    }
}   
user2138160
  • 279
  • 1
  • 5
  • 14

2 Answers2

2

This should work:

$is_unique = false;
$num = false;
while (!$is_unique){
    $num = rand(1,5);
    $sel_query  = "SELECT id from test where id = " . $num; 
    $result2 =  $con->query($sel_query) or die($conn->error);
    if (!mysqli_fetch_array($result2)){
        $is_unique = true;
    }
}
echo "Unique number is " . $num;   

But if there aren't any more possible unique numbers, it will loop forever.

Jodes
  • 14,118
  • 26
  • 97
  • 156
1

I know this is a bit old, but I found this question after needing a similar answer. I've taken Jodes's answer and updated it slightly, so that it won't run forever, is a function that returns the number, and accepts a mysqli connection as $mysqli:

function getUniqueNumber($mysqli)
{
    $is_unique = false;
    $num = false;
    $times_run = 0;
    while (!$is_unique)
    {
        if($times_run > 10)
        {
            echo "Run too many times, dying.";
            die();
        }
        $num = rand(1,5);
        $sel_query  = "SELECT id from test where id = " . $num; 
        $result2 =  $mysqli->query($sel_query) or die($mysqli->error);
        if (!mysqli_fetch_array($result2))
        {
            $is_unique = true;
        }
        $times_run++;
    }
    return $num;
}
Dwebtron
  • 777
  • 13
  • 27