Avatar ·

PHP date format for inserting into MySQL DATETIME field: how to avoid errors?

Hello everyone! I'm a beginner in PHP and MySQL, and I have a problem with saving dates to the database.

\n\n

I have a form where the user enters a date in the format dd.mm.yyyy (e.g., 25.12.2023). I want to save this date in a DATETIME field in MySQL. I'm using the PHP date() function for formatting, but nothing works correctly.

\n\n

Here is my code:

\n\n
<?php\n$user_date = $_POST['user_date']; // Comes as "25.12.2023"\n$formatted_date = date('Y-m-d H:i:s', strtotime($user_date));\n\n$query = "INSERT INTO events (event_date) VALUES ('$formatted_date')";\nmysqli_query($conn, $query);\n?>\n
\n\n

The problem is that the database records 1970-01-01 00:00:00 or an empty string. I tried