Search Posts

Efficient check if value exists in database

I want to generate unique value and save it in database.

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

I have two options (PSEUDO CODE):

1)

$allValues = 'SELECT unique_number FROM table'; //EXAMPLE!

$number = generateRandomString();

while(in_array(number, $allValues)) {
    $number = generateRandomString();
}

2)

function getUniqueNumber($uniqueNumber) {
    return 'SELECT unique_number FROM table WHERE unique_number = ' . $uniqueNumber; //EXAMPLE!
}

$number = generateRandomString();

while(getUniqueNumber($unique)) {
    $number = generateRandomString();
}

But both method are inefficient if I have over 100,000 records.

Is better way to check if value exists in database and generate new if exists?

I can use also Doctrine for this.

Source: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *