I have a table with multiple users. Today users are in plane text password.
Now I created a new column with VARCHAR (256)
to put the password hash of each user in a column called password
.
I made a PHP that obtains every user and make an update corresponding with the password hash:
<?php
require("Db.class.php");
require("password.php");
$db = new Db();
$result = $db->query("SELECT idUser, pass FROM user");
if(count($result) == 0){
echo "Error!";
$db->CloseConnection();
}
else if(count($result) > 0){
foreach($result as $user){
$passDB = $user["pass"];
$idUser = $user["idUser"];
$hash = password_hash($passDB, PASSWORD_BCRYPT);
$resultUser = $db->query("UPDATE user SET password = :hash WHERE idUser = :idUser",
array("hash" => $hash, "idUser" => $idUser));
}
$db->CloseConnection();
}
?>
The php works for a few rows. Then, the SQL not update following rows because is too inefficient.
Is there a better way to do what I want? I have to mix php with mysql because I have to convert plain text password with password_hash function from the library: password compat
In this case you can use INSERT...ON DUPLICATE KEY UPDATE to do this in a single query. http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
The code below assumes isUser is a PRIMARY KEY or is UNIQUE column in the table.
<?php
require("Db.class.php");
require("password.php");
$db = new Db();
$result = $db->query("SELECT idUser, pass FROM user");
if(count($result) == 0){
echo "Error!";
$db->CloseConnection();
}
else if(count($result) > 0){
$str="INSERT INTO user (idUser,pass,password) VALUES ";
foreach($result as $user){
$passDB = $user["pass"];
$idUser = $user["idUser"];
$hash = password_hash($passDB, PASSWORD_BCRYPT);
$str.="('".$idUser."','".$passDB."','".$hash."'),";
}
$str=rtrim($str,",");
$str.="ON DUPLICATE KEY UPDATE password=VALUES(password);";
$resultUser = $db->query($str);
$db->CloseConnection();
}
?>
I think this article maybe useful.
On your query
$resultUser = $db->query("UPDATE user SET password = PASSWORD(:hash)
WHERE idUser = :idUser",
Refer here http://dev.mysql.com/doc/refman/5.7/en/password-hashing.html then you don't need to convert at php and pass again
or if you don't want to re do array.
$resultUser = $db->query("UPDATE user SET password = PASSWORD('".$hash."')
WHERE idUser = '".$idUser."'",
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.