我尝试使用while循环向另一个表中的每次提取插入一行表。我目前的代码将第一个用户数据插入到数据库中。
如果插入查询在循环之外,它将输入最后的用户数据。它必须是遍历数组的问题。有没有办法可以为循环的每次传递索引数组值?
$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();
while($rows = $statement->fetch()){
$salted = $sso_key . $companyId;
$hash = hash('sha1',$salted,true);
$saltedHash = substr($hash,0,16);
$iv = substr(md5(microtime()),rand(0,16),16); //Generate random 16 bit string
$user_data = array(
"user_id" => $rows['id'],
"first_name" => $rows['first_name'],
"last_name" => $rows['last_name'],
"email" => $rows['email'],
"position" => $rows['type']);
$data = json_encode($user_data);
$data = $iv . $data;
$pad = 16 - (strlen($data) % 16);
$data = $data . str_repeat(chr($pad), $pad);
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128,'','cbc','');
mcrypt_generic_init($cipher, $saltedHash, $iv);
$encryptedData = mcrypt_generic($cipher,$data);
mcrypt_generic_deinit($cipher);
$encryptedData = base64_encode($encryptedData);
$token = array(
"token" => $encryptedData
);
$token_data = json_encode($token);
echo "
<br>Here is the token for ".$user_data['first_name'].", ".$user_data['last_name']."
".$user_data['email'] ." :
" . $token['token'];
$query = "INSERT INTO another_table
(token ,first_name,last_name,email,position)
VALUES (:token, :first_name,
:last_name, :email, :position)";
$statement = $db->prepare($query);
$statement->bindValue(':token', $token['token']);
$statement->bindValue(':first_name', $user_data['first_name']);
$statement->bindValue(':last_name', $user_data['last_name']);
$statement->bindValue(':email', $user_data['email']);
$statement->bindValue(':position', $user_data['position']);
$statement->execute();
}
?>
答案 0 :(得分:0)
将代码简化为基础,你有这个:
$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();
while($rows = $statement->fetch()){
// .. stuff ..
$query = "INSERT INTO another_table
(token ,first_name,last_name,email,position)
VALUES (:token, :first_name,
:last_name, :email, :position)";
$statement = $db->prepare($query);
$statement->bindValue(':token', $token['token']);
$statement->bindValue(':first_name', $user_data['first_name']);
$statement->bindValue(':last_name', $user_data['last_name']);
$statement->bindValue(':email', $user_data['email']);
$statement->bindValue(':position', $user_data['position']);
$statement->execute();
}
看到问题了吗?好的,这是一个修复它的提示:
$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$statement->execute();
while($row = $statement->fetch()){
$query = ".. stuff ..";
$OTHER_statement = $db->prepare($query);
// .. stuff ..
$OTHER_statement->execute();
}
在while循环中,您使用insert sql覆盖变量$statement
。这有效地过早地结束了你的while循环。如果第二个sql是另一个SELECT,也可能导致一些严重的意外和意外问题。