0

I tried to generate random number and check it in DB if it exist, then try again until the result obtained then break using the following code

But its not working, I don't know where is the issue with while loop

<?
  $digit=mt_rand(11, 999);
  $sql=mysqli_query($connect, "SELECT `number` FROM `db_name` WHERE  `number` =='$digit' ");

  while($num=mysqli_num_rows($sql))
  {
    if($num==1)
    {
      echo "Not good";
    }
    else
    {
      echo "Good ".$digit;
      break;
    }
  }
?>

Also I tried this code but when the number is available in DB, the script stop and not trying to generate another number

<?
  $digital=mt_rand(11, 999);
  $sql=mysqli_query($connect, "SELECT `number` FROM `db_name` WHERE  `number` ='$digital'");
  $i=0;

  while($i<=10000)
  {
    $num=mysqli_num_rows($sql);
    if($num==1)
    {
      $i++;
    }
    else
    {
      echo "Good ".$digital;
      break;
    }
  }
?>
5
  • Is not number in db, integer , while comparing you are quoting as string. Commented Jan 26, 2018 at 5:05
  • 1) You're selecting all the numbers that don't match your number, you should be selecting only the record that does match your number. 2) You're comparing the number of returned rows to your number while you should just be checking whether the number of returned rows is greater than zero. Commented Jan 26, 2018 at 5:06
  • I modified the code but still not working Commented Jan 26, 2018 at 5:08
  • Did you try my answer below. There might be connection issue also. It is always better to use die(mysql_error) on debug mode. What error are you getting will make easier to understand issue. Commented Jan 26, 2018 at 5:11
  • With the modified code as per my post, nothing appear only black page. I added the db info before the script as well. Commented Jan 26, 2018 at 5:14

1 Answer 1

1

Finally

I solved it by the below code

<?
$unique_ref_found = false;
while (!$unique_ref_found) {  
$digital = mt_rand(11, 999);  
$sql = mysqli_query($connect, "SELECT `number` FROM `db_name` WHERE  `number` ='$digital'");
$num= mysqli_num_rows($sql); 
    if ($num==0) {  
       $unique_ref_found = true;  
      }
  }  

echo $digital; 


?>
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.