I have written some PHP PDO code to let my website users update their details.
The code is meant to skip any blank input fields and only update those that the user has entered details into.
It's working fine, apart from the password field. When I leave all the form blank and press 'Save', everything stays the same apart from the password that still changes.
Please see my code below.
I want the code to update the password if the user has entered a new one, otherwise I want to it keep the one that is already in the mysql table (The password is hashed).
Is anyone able to advise me what the correct code would be for this?
PHP
<?php
require('../../../private_html/db_connection/connection.php');
session_start();
$ID = $_SESSION['ID'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE user_accounts SET first_name = COALESCE(NULLIF(:fname, ''),first_name), surname = COALESCE(NULLIF(:sname, ''),surname), display_name = COALESCE(NULLIF(:dname, ''),display_name), email = COALESCE(NULLIF(:email, ''),email), password = COALESCE(NULLIF(:password, ''),password) WHERE account_number='$ID'";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':fname', $_POST['fname']);
$stmt->bindParam(':sname', $_POST['sname']);
$stmt->bindParam(':dname', $_POST['dname']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_DEFAULT));
$stmt->execute();
$query = $conn->prepare("SELECT * FROM user_accounts WHERE account_number='$ID'");
$query->execute();
if(($row = $query->fetch())){
$_SESSION['ID'] = $row['account_number'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['surname'] = $row['surname'];
$_SESSION['display_name'] = $row['display_name'];
$_SESSION['email'] = $row['email'];
header("Location: ../../myaccount/mydetails/mydetails.php");
}
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
exit();
}
?>