Skip to content
PHP Logo

In PHP, how can the formatting of a date retrieved from MySQL be done directly in the query using the DATE_FORMAT() function?

When retrieving a date from MySQL in PHP, you can format the date directly in the query using the DATE_FORMAT() function. This allows you to retrieve the date in the desired format without needing to manipulate it in PHP code. Simply use the DATE_FORMAT() function in your SQL query to format the date according to your preferences.

php
// Example query to retrieve a date from MySQL in a specific format
$query = "SELECT DATE_FORMAT(date_column, '%Y-%m-%d') AS formatted_date FROM table_name";
$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['formatted_date'] . "<br>";
    }
} else {
    echo "Error: " . mysqli_error($connection);
}