2

Below is my code to check if the generated random number is available in the database. If the $smsCode is already in the database, then generate a new random number. But it is not working as expected.

$smsCode = 7552;
        $query = "SELECT * FROM appointment WHERE sms_code = '$smsCode'";
        while($conn->query($query) === TRUE){
            $smsCode = rand(1000,9999);
            $query = "SELECT * FROM appointment WHERE sms_code = '$smsCode'";
            $conn->query($query);
        }
$sql = "INSERT INTO appointment(number) VALUES('$smsCode');

$smsCode = 7552 is already in the database but it keeps storing 7552 into the database instead of generating a new number to be stored in the database.

3 Answers 3

2
<?php
$sms_code=rand(1000,9999);
$cond=True;
while($cond){
    $query = "SELECT * FROM appointment WHERE sms_code = '$smsCode'";
    $result = $conn->query($query);
    if(mysql_num_rows($result)>0)
    {
        $sms_code=rand(1000,9999);
    }
    else
    {
        $cond=False;
    }
}
$sql = "INSERT INTO appointment(number) VALUES('$smsCode')";
?>
Sign up to request clarification or add additional context in comments.

1 Comment

This is NOT "race condition" safe.
1

If the result of your first query returns a valid result it doesn't return true. The query() function only returns false if it fails, see PHP manual. So the condition of your while-loop where you make a comparison to the boolean true (cause of strict type comparions with three =) will never be true and so no new value is assigned to $smsCode.

Try something like this

$smsCode = 7552;

while(true) {

    $query = "SELECT * FROM appointment WHERE sms_code = '$smsCode'";
    if($conn->query($query) === false) {
      $sql = "INSERT INTO appointment(number) VALUES('$smsCode')";
      break;
    } else {
      $smsCode = rand(1000,9999);
    }
}

This should generate a new code every time you don't have row in your database with that code.

4 Comments

You need to add " to the end of $sql
Ops didn't copied the whole query :O Thanks
You need to place it before ;, but anyways, its more efficient than my code :)
A do { ... } while () would be more sensible syntax. BUT this approach is NOT "race condition" safe.
0

you can try this

$date = date_create();
$smsCode = date_timestamp_get($date);

each time it will give you an unique random numbers

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.