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);