0
I’m trying to create a PHP function where it checks if the user id already exists, the id is created with the function rand, but even having very few chances of appearing the same id, the chances still exist! then to never have headache with that part, I have to check if the id has been inserted.
What I’m trying to do is:
Check if id already exists: if yes, generates a new id and checks again. if not, follow the code.
How to create this the right way?
$id_usuario = rand(1000000, 9999999);
$consultaBanco = mysqli_query($conecta, "SELECT id_usuario FROM site_user WHERE id_usuario = '".$id_usuario."'") or die (mysqli_error($consultaBanco));
$verificaBanco = mysqli_num_rows($consultaBanco);
if ($verificaBanco > 0){
$id_usuario = rand(1000000, 9999999);
return $consultaBanco;
}
It would not be easier to set in the table
site_userthe columnid_usuarioasAUTO_INCREMENT? 'Cause then there’s no way id repeated!– NoobSaibot
If there are only a few left on this Rand it will take a lot of work to find a non-repeated one! Imagine if there is only one left. @wmsouza solution is the best possible, follow the code and let the database generate the id
– user60252
That one
id_usuarioneed (or will) be used directly by the user (something he needs to decorate)? or will be visible only to the system?– Juven_v