April 1, 2012

How can I generate a number that never be the same again(repeated) PHP

Question by yeah its me

Possible Duplicate:
Algorithm for generating a random number

is posible to generate a random number that is never repeated??

Is there a solution in php? or codeIgniter?

for example if i need to generate a random never repeated id for every user, how can i be sure that no user will have the same id?

Answer by Starx

Clearly speaking, there is always a chance for a number since every form is generated from same algorithm generally.

The safest way would be to check you database to ensure that, if an id is already taken like:

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$result = mysql_query($query);
if(mysql_num_rows($result)) { 
  //the id is present
}

It will be better if you use mysqli instead

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "i", $id);
mysql_stmt_execute($stmt);
if(mysql_stmt_num_rows($stmt))
  //the id is present
}  
mysqli_stmt_close($stmt);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!