我有一个标准的MySQL数据库,大约有60行(如用户帐户)。当我第一次创建它时,我错误地将会话ID与简单帐户ID相同,现在我想修复我的错误,我显然不会通过60行来重置它们不同的安全会话ID,所以我是写这个功能:
function generate_sessionid(){
return bin2hex(openssl_random_pseudo_bytes(32));
}
function assign_all_sessionids(){
$sessionid = generate_sessionid();
$conn = sql_connect();
$result = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE 1");
sql_disconnect($conn);
}
assign_all_sessionids();
问题:数据库中的每个帐户都会获得与其他帐户相同的随机会话ID。如何使每个行重新调用函数以使其对每一行都是随机的?
答案 0 :(得分:1)
尝试从DB中获取用户的计数并简单地执行N次
function assign_all_sessionids(){
$conn = sql_connect();
// getting users count
// here just change 'id' to your id parameter
$result = mysqli_query($conn, "SELECT id FROM accounts");
$arr = $result->fetch_array(MYSQLI_NUM);
// executing N times
for($i = 0; $i < $result->num_rows; $i++){
$sessionid = generate_sessionid();
// here just change 'id' to your id parameter again
mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE `id`=".$arr[$i]);
}
sql_disconnect($conn);
}
答案 1 :(得分:0)
首先将所有会话ID设置为NULL
:
UPDATE accounts
SET sessionid = NULL;
然后,在循环内部:
UPDATE accounts
SET sessionid = '$sessionid'
WHERE sessionid IS NOT NULL
LIMIT 1;
答案 2 :(得分:0)
通常,您不希望在循环中执行查询,但是在这种情况下,您需要获取所有当前唯一标识符,循环并生成新标识符,然后更新一个:
function assign_all_sessionids(){
$conn = mysqli_connect('whatever...');
$select = mysqli_query($conn, "SELECT sessionid FROM accounts");
while(list($id) = mysqli_fetch_assoc($select)) {
$sessionid = generate_sessionid();
$update = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE sessionid='$id'");
}
}