When a user signs up to my website, for example, I create a unique string of length 40 and insert it into the database. We then send an email to the newly signed up user containing this unique string in the form of an URL, and this all works fine. But how do you create and insert this signup entity ensuring that the field with the unique property is actually unique?
My current approach is as follows:
$key = '';
$repeat = true;
while ($repeat) {
$key = generate_hash(40);
$is_unique = (count($model->get_by_key($key)) === 0) ? true : false;
$repeat = ($is_unique) ? false : true;
}
// At this point I know the key is unique and can insert it...
I am not happy with this code, as I try to avoid while loops in general. Is there a better way to achieve what I am doing here?
The bottom line is that the MySQL field containing these keys has the unique property and I need to know that no unique-violations will occur when inserting these keys.