Search code examples
phpmysqlpassword-hash

Error Updating Old Password with with password_hash


I've a problem when updating the old password with the new one password_hash, it always said Old password is wrong.

The table: pegawai

Field: nokom, nama, uol1

Here's my code:

<?php session_start();
require "config.php";

  $nokom    = $_POST['nokom'];
  $pswlama  = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
  $pswbaru  = password_hash($_POST['pswbaru'], PASSWORD_DEFAULT);

  $cari     = "SELECT * FROM pegawai WHERE nokom ='".$nokom."'";
  $result   = mysqli_query($conn,$cari);
  if (mysqli_num_rows($result) > 0)
  {
    while ($data = mysqli_fetch_array($result))
    {
      if(password_verify($pswlama, $data['uol1']))
      {
        $perintah = "UPDATE pegawai SET uol1 = '$pswbaru' WHERE nokom = '$nokom' ";
        if (mysqli_query($conn, $perintah)) 
        {
           echo "<script>alert('Success');location.replace('home.php')</script>";
        } 
          else 
          {
            echo "Error updating record: " . mysqli_error($conn);
          }
      }
        else
        {
          echo "<li>Old password is wrong!</li>";
        }
    }
  }
  else
  {
    echo "Data not found";
  }
?>

Any help will be great, thanks.


Solution

  • change this

     $pswlama  = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
    

    to this. password_verify will handle the rest.

     $pswlama  = $_POST['pswlama'];
    

    keep the rest of your code the same.