I have a code which generates a 6 digit random number with the code `mt_rand(100000,999999);` and stores it in the variable `$student_id`. I check if the number exists in the database with the following code.

```
if($stmt = mysqli_prepare($connect, "SELECT id FROM students WHERE id = ? LIMIT 1")) {
    mysqli_stmt_bind_param($stmt, "i", $student_id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $db_id);
    mysqli_stmt_fetch($stmt);
}

if(mysqli_stmt_num_rows($stmt) == 1) {
    echo "The ID exists.";
} else {
    // Insert $student_id into database
}

```

This code can insert the ID into the database if `mysqli_stmt_num_rows($stmt) == 0`. But, if the ID already exists, it won't generate a new 6 digit random ID, it won't check if that ID already exists in the database, etc. I can imagine that I would have to use some kind of loop which will keep generating a random ID untill it doesn't exists in the database and then insert it into the database. I've read about a few loops (like `while` or `for`), but I don't have any idea how to use them.

Can anyone help me out with this or help me in the right direction?

Cheers