Loop in PHP to check user id

Asked

Viewed 89 times

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_user the column id_usuario as AUTO_INCREMENT ? 'Cause then there’s no way id repeated!

  • 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

  • That one id_usuario need (or will) be used directly by the user (something he needs to decorate)? or will be visible only to the system?

1 answer

0

I imagine the reason you are doing this draw is that you want a 7 digit id (in the format xxxxxxx). What at first glance would not be possible with a primary auto key increment in the database (but only at first glance).

You can set where the auto increment will start from (for example, from 1000000). This can be done as such (running in the database administration interface, for example in phpmyadmin, if you are using, either by terminal, or even by php code (only once!)):

ALTER TABLE site_user AUTO_INCREMENT=1000000;

This will make everything inserted with the Insert is incremented from the value set in the above instruction.

But there is only one problem, if the id user field is not yet the primary key, the auto increment will not work. Then we have to make it the primary key (if not yet):

ALTER TABLE site_user ADD PRIMARY KEY(id_usuario);

And finally say that id_usuario is auto_increment. Sort of like this:

ALTER TABLE site_user MODIFY COLUMN id_usuario AUTO_INCREMENT;

After all this you can do the Inserts without having to worry about doing draw.

  • this part I know, but I really need Rand to create a unique id for the user that is not in sequence, yes, random

Browser other questions tagged

You are not signed in. Login or sign up in order to post.