What are the best practices for storing and displaying date and time information in PHP when interacting with a MySQL database?
When storing and displaying date and time information in PHP when interacting with a MySQL database, it is best practice to use the datetime data type in MySQL for storing dates and times. When fetching data from the database, you should use PHP's DateTime class to format and display the date and time information in the desired format.
// Storing date and time information in MySQL database
$date = new DateTime();
$datetime = $date->format('Y-m-d H:i:s');
$query = "INSERT INTO table_name (datetime_column) VALUES ('$datetime')";
// Execute the query
// Fetching and displaying date and time information from MySQL database
$query = "SELECT datetime_column FROM table_name";
$result = // Execute the query and fetch the result
while($row = mysqli_fetch_assoc($result)) {
$datetime = new DateTime($row['datetime_column']);
echo $datetime->format('Y-m-d H:i:s');
}