What are the best practices for storing and updating user login dates in a PHP database?

When storing and updating user login dates in a PHP database, it is important to ensure that the data is accurate and up-to-date. One best practice is to use a timestamp data type in the database to store the login dates. When updating the login date, you can use SQL queries to update the timestamp value for the specific user.

// Update user login date in the database
$user_id = 1; // User ID of the user logging in
$login_date = date('Y-m-d H:i:s'); // Current date and time

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Update user login date
$sql = "UPDATE users SET last_login = '$login_date' WHERE id = $user_id";

if ($connection->query($sql) === TRUE) {
    echo "User login date updated successfully";
} else {
    echo "Error updating login date: " . $connection->error;
}

// Close database connection
$connection->close();