[英]PHP do/while Prepared Statement failing
我有一個代碼,打算對我的數據庫進行檢查,以查看給定值是否唯一,如果是,則將其插入數據庫。 如果不是唯一的,請重復該過程,直到找到唯一的值為止。
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
首先,我不知道為什么我會從此代碼中得到重復的錯誤-這是怎么回事? 其次,如果我確實有重復的機會,應該重新生成它,然后重試直到它起作用-但這顯然沒有發生。
有什么線索嗎?
詳細說明一下...您的腳本生成了一個隨機數,該隨機數將在80%的時間以上超過一個int的最大值。 用於測試是否已使用user_id的查詢將返回false(mysql允許您在列的范圍限制之外進行查詢,它只是說沒有具有該id的記錄),但是插入查詢將失敗,因為該數字減小到最大INT大小。 要解決此問題,您可以切換到BIGINT或限制您的隨機范圍。
嘗試將您的ID列更改為BIGINT vs INT,因為您似乎正在嘗試生成大於INT類型容量的隨機數。 這就是為什么它將其降至INT最大數字2147483647的原因。
限制mt_rand(1000000000,2147483647);
int
數據類型不能處理的更多。
最好使用auto_increment字段,因此只要用戶名是唯一的,您就可以插入每個記錄。 如果確實需要,可以使用mysql_insert_id()獲取最后插入的記錄的ID。
如果您確實希望數字隨機出現,則可以使用某種記號(例如xor或特定的位洗牌)來生成另一個數字,您始終可以將其計算回存儲在數據庫中的真實用戶ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.