Current Location: Home> Latest Articles> Handling date format issues for query results in mysqli_result::fetch_column

Handling date format issues for query results in mysqli_result::fetch_column

gitbox 2025-05-26

1. Basic example: Use fetch_column to get date field

Suppose we have a table called events , where an event_date field is of type DATETIME.

 <?php
$mysqli = new mysqli("gitbox.net", "username", "password", "database");

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

$sql = "SELECT event_date FROM events WHERE id = 1";
$result = $mysqli->query($sql);

if ($result) {
    // Directly remove the date field
    $date = $result->fetch_column();
    echo "Original date format: " . $date;
} else {
    echo "Query failed: " . $mysqli->error;
}

$mysqli->close();
?>

The output may be:

 Original date format: 2025-05-23 14:30:00

2. Question: How to format dates?

If you only want the year, month and day part "2025-05-23" , or want to output it in other formats, such as "23 May 2025" , you need to process the results.


3. Solution 1: Use PHP's DateTime class to handle it

 <?php
$date = $result->fetch_column();

$dateObj = new DateTime($date);
// Format to display only year, month, day
$formattedDate = $dateObj->format('Y-m-d');
echo "Formatted date: " . $formattedDate;
?>

This outputs:

 Formatted date: 2025-05-23

or:

 $formattedDate = $dateObj->format('d M Y');
echo "Formatted date: " . $formattedDate;

Output:

 Formatted date: 23 May 2025

4. Solution 2: Format dates during SQL query

If you want the database to directly return the formatted string, you can use MySQL's DATE_FORMAT function:

 <?php
$sql = "SELECT DATE_FORMAT(event_date, '%Y-%m-%d') AS event_date FROM events WHERE id = 1";
$result = $mysqli->query($sql);

if ($result) {
    $date = $result->fetch_column();
    echo "SQL Formatted date: " . $date;
}
?>

Output:

 SQL Formatted date: 2025-05-23

5. Solution 3: Intercept with string functions (not recommended)

Although substr can be used to directly intercept the first 10 characters of the date string, it is not flexible enough and prone to errors.

 $date = $result->fetch_column();
$shortDate = substr($date, 0, 10);
echo "The date of intercept: " . $shortDate;

Summarize

  • The date returned by mysqli_result::fetch_column is in string format and needs to be converted before customization can be customized.

  • Using PHP DateTime is the recommended method, which is both flexible and safe.

  • It can also be formatted directly in SQL queries to reduce processing on the PHP side.

  • Avoid intercepting dates with strings unless it is determined that the format is stable.

Reasonable choice of processing methods can make your date display more in line with business needs, while ensuring the maintainability and robustness of the code.