简体   繁体   中英

Updating current passwords with password hashing

I'm trying to run password_hash on current password values in my database...

$mysqli->query("UPDATE users SET password = '" . password_hash('password', PASSWORD_DEFAULT) . "');

I'm getting no error, but the password does not work after the update as expected. The only thing I can think of is the above query is not getting the current password value from the table.

No need for prepared statements as I'm just mucking about locally for this one.

You can't mix PHP and SQL like this. password_hash is a PHP function. You need to fetch the user data into PHP, iterate over it and save each record into the database. Use SQL transactions when doing so.

// Remember to always enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset

$users = $mysqli->query('SELECT Id, password FROM users');

// start transaction and prepare a statement
$mysqli->begin_transaction();
$stmt = $mysqli->prepare('UPDATE users SET `password`=? WHERE Id=?');

foreach ($users as $user) {
    // make a hash out of the password
    $hash = password_hash($user['password'], PASSWORD_DEFAULT);
    $stmt->bind_param('ss', $hash, $user['Id']);
    $stmt->execute();
}

// commit the data to DB and end transaction
$mysqli->commit();

Always use prepared statements. There's absolutely no excuse not to use parameter binding. If you were to use parameter binding from the start you would have noticed much quicker that your approach is flawed. Now you have changed all passwords to the string password ; every account has the same password.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM