Are there any best practices for ensuring that randomly generated IDs correspond to existing IDs in a database table in PHP?

When generating random IDs in PHP, it is important to ensure that the generated IDs do not already exist in the database table to avoid duplication. One way to achieve this is by querying the database to check if the generated ID already exists before inserting it. If the ID already exists, generate a new random ID until a unique one is found.

// Generate a random ID
$random_id = generateRandomID();

// Check if the random ID already exists in the database
while (idExists($random_id)) {
    $random_id = generateRandomID();
}

// Insert the unique random ID into the database
insertID($random_id);

function generateRandomID() {
    return mt_rand(100000, 999999); // Generate a random 6-digit number
}

function idExists($id) {
    // Query the database to check if the ID already exists
    // Return true if the ID exists, false otherwise
}

function insertID($id) {
    // Insert the ID into the database table
}