我有一个代码打算在我的数据库上运行一个检查,看看给定的值是否唯一,如果唯一,就将它插入到数据库中。如果它不是唯一的,请重复这个过程,直到找到唯一的值。
do {
// Generate a new user ID (15 numbers) and check to make sure it doesn't already exist.
$new_user_id = mt_rand(1000000000, 9999999999);
// Generate a fake Login Email address and check to make sure it doesn't already exist.
$new_username = rand_str(13, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890');
$new_username_email = 'BP' . $new_username . '@web.com';
// Generate a new fake password
$new_password = rand_str(15, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()');
// Check to make sure the extremely random Username and user ID doesn't already exist in the database
// On the off chance that it does, we need to regenerate and try again.
$preparedStatement = $connection->prepare("SELECT user_id, username FROM `{$mysql_table}` WHERE user_id = :new_user_id OR username = :new_username");
$preparedStatement->execute(array(':new_user_id' => $new_user_id, ':new_username' => $new_username_email));
$result_2 = $preparedStatement->fetchAll();
//TODO Not sure if this is actually working if there is a duplicate entry
} while (!empty($result_2));
// Once it is unique, insert the values into the database
$preparedStatement = $connection->prepare(
"INSERT INTO `{$mysql_table}` (
open_id,
user_id,
username,
password
) VALUES (
:open_id_value,
:user_id_value,
:username_value,
:password_value
)");
if (!$preparedStatement->execute(array(
':open_id_value' => $_SESSION['user'],
':user_id_value' => $new_user_id,
':username_value' => $new_username_email,
':password_value' => $new_password
))) {
$arr = $preparedStatement->errorInfo();
die(print_r($arr));
} else {
// Send the new user to the account settings page, where they can set up their account information
$_SESSION['new_user'] = 1;
//echo 'You are a new user!';
header("Location: /account-settings/");
exit;
}
我得到的问题是,Mt_-Rand生成的值表示它是一个副本。
Array ( [0] => 23000 [1] => 1062 [2] => Duplicate entry '2147483647' for key 1 ) 1
首先,我不知道为什么我会从这个代码中得到一个重复的错误-它有什么问题?第二,我有机会得到一个副本,它应该重新生成,然后再试一次,直到它工作为止——但这显然没有发生。
有什么线索吗?