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; 

        }
    }
}   
4
  • what is the column of the rand number in the DB you can simply do a search for it instead of looping through... Commented Mar 12, 2013 at 4:14
  • that's what i'm trying to do but its not working@allen Commented Mar 12, 2013 at 4:14
  • This might help you: stackoverflow.com/questions/8834493/… Commented Mar 12, 2013 at 4:19
  • 1
    What are you trying to accomplish? Just fetch a random row from a table? What do mean by ...but it's not UNIQUE? Commented Mar 12, 2013 at 4:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i got an error: Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
There's some sort of error then. I've edited it, try it now, it should output the error.
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;
}

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.