简体   繁体   中英

Test if number exist in database, create new one if it exists

I have a hurtle I just can't figure out.

I want my code to:

  1. Create a random number
  2. Test if it exist in the database
  3. If it exist, create a new random number og do number 2. again.
  4. If it don't exist, create it in the database.

I've tried the following code, which I found in a similar problem on Stackoverflow, but I just can't figure this out:

$key = true;

while($key){

    $unique_number_new = rand(1000,9999);
    $result = mysql_query("SELECT * FROM brugere WHERE medlemsnummer = $unique_number_new");

    if(mysql_num_rows($result) > 0) {   
        $key = false;   
        // Allready exists

    } else {    
        $key = true;
        // Create in database
    }

        echo "Code done! - " . $unique_number_new;
}

The problem is, it gives me multiple numbers (see https://www.dance4fun.dk/test_folder/number_test.php )

How can I create a code that does the 4 above mentioned, steps?

Hope you can help me out with this!

A reason why your code didnt work:

  • You had 'true' set as the not found result, so if it didnt find anything, it would continue looping.
  • You had the echo showing you the code no matter what.

This is a way to achieve what you listed out:

do {
    $unique_num = mt_rand(1000,9999);
    // NOTE: changed mysql_query to use mysqli! (prepared statement not required here)
    $exists = mysqli_fetch_row(
                  mysqli_query(
                      $connection,
                      "SELECT COUNT(*) FROM brugere WHERE medlemsnummer = $unique_num"
                  )
              )[0];// [0] means grab column result
} while($exists);

echo "Code done! - " . $unique_num;

This will always run the code once (do), and will repeat if the random number was found in the database. Once it is not found in the database, you then have a random number in a variable to use as your whim after the while loop finishes.

For these things, its a good idea to add a fail-safe:

$c = 0;
do {
   $c++;
   /// other code
} while ($exists and $c < 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM