Skip to content
Advertisement

Couldn’t UPDATE password in PHP MySQL

I couldn’t update password to a new one in the change password page and there is no error at all so couldn’t found which is the incorrect part. I’ve checked in MySQL table, and it is not updated. Can someone assist to find it out? Thank you.

PHP code

 include "../setting/config.php";

 session_start();

$btnchange = filter_input(INPUT_POST, "btnchange");

if(isset($btnchange))
{
    $username = filter_input(INPUT_POST, "username");
    $password = filter_input(INPUT_POST, "password");

    $query2 = "SELECT username from registered_accounts where username='$username'AND password='$password'";
    $query_run=mysqli_query($conn, $query2);
    $level = mysqli_fetch_array($query_run);
    if(count(fetchAll($query2)) > 0){ //this is to catch unknown error.
                  foreach(fetchAll($query2) as $row){
                    if ($row['username'] == $username && $row['password'] == $password) 
                    {
                        $update_query2= "UPDATE registered_accounts set password='$password' where username='$username'";
                        $update_query_run=mysqli_query($conn, $update_query2);
                        if ($update_query2)
                        {
                            echo "<script>alert('Password has been changed successfully.')</script>";
                        }
                        else{
                            echo "<script>alert('Password has been failed to change.')</script>";
                        }
}
}
}
}
?>

Body

<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
    <input type="text" class="text" name="username" placeholder="Username" value="" required autofocus>
    <input type="password" placeholder="Password" name="password" value="" required autofocus>
    <div class="submit"><input type="submit" value="Submit" name="btnchange"></div>
</form>

registered_accounts table Table Structure

Advertisement

Answer

You need to update this new password. And this new password is not current password of the queried user. So the select query is failing to retrieve any result. Remove AND password=’$password’ from $query2, like this:

    $query2 = "SELECT username from registered_accounts where username='$username'";

and also remove the if statement, as there is no need to check again.

    if ($row['username'] == $username && $row['password'] == $password)

Hope this will help, But I also suggest you to use prepared statement to prevent from SQL Injections.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement