What are the best practices for handling date inputs from users in PHP to prevent issues with date storage in a MySQL database?

When handling date inputs from users in PHP to store in a MySQL database, it is important to validate and format the date properly to prevent issues with date storage. One common approach is to use the DateTime class in PHP to parse and validate the user input before inserting it into the database.

// Validate and format user input date
$user_input_date = $_POST['date'];
$date = DateTime::createFromFormat('Y-m-d', $user_input_date);

if ($date) {
    $formatted_date = $date->format('Y-m-d');
    
    // Insert formatted date into MySQL database
    $query = "INSERT INTO table_name (date_column) VALUES ('$formatted_date')";
    // Execute query
} else {
    // Handle invalid date input
    echo "Invalid date format";
}