How can i check if a id exists in a mysql database, and if it does: create a new id and check over again. I have the following code to create a id:
$length = 10;
$id = '';
for ($i = 0; $i < $length; $i++) {
$id .= chr(rand(ord('0'), ord('9')));
}
To check if the id exists i use the code below:
$database->query('SELECT user_id FROM users
WHERE public_id = ':public_id',array(':public_id' => $public_id)');
if($database->count() >= '1') {
//create a new id
} else { }
What you’re trying to do is not considered a “best practice”, as (theoretically) you could create an infinite loop (creating a random ID, then checking for existence could “hit” on each iteration).
A better solution to create unique IDs is to set a column as your primary key, and increment upon each new insert.
If you want another column to be unique, you can define that column to be unique as well, but you won’t have to rely on “random” strings.