Loop in PHP to check user id

0

I'm trying to create a function in PHP where it checks if the id of the user already exists, the id is created with the function rand , but even though there are very few chances of the same id appearing, chances are still there! so to never have headache with that part, I have to check if the id has already been inserted.

What I'm trying to do is:

Verify that the id already exists: if yes, generate a new id and check 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;
}
    
asked by anonymous 24.12.2017 / 05:43

1 answer

0

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

You can tell where the auto increment will start (for example, from 1000000). This can be done like this (running in the admin admin interface, for example in phpmyadmin, if you are using, or through the terminal, or even php code (just once!)):

ALTER TABLE site_user AUTO_INCREMENT=1000000;

This will make everything inserted with insert incremented from the value set in the above statement.

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

ALTER TABLE site_user ADD PRIMARY KEY(id_usuario);

And finally say that userid is auto_increment . More or less 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 drawing lots.

    
24.12.2017 / 14:43