Search code examples
phpmysqldatetimedate-formatting

Formatting a DateTime column in PHP


I have a column that stores DateTime in a MySQL database. I want to compare the Date part (and not the time) to the current day. I am not sure what method to use as I am very new to PHP.

$today=date("Y-m-d");
$sql="SELECT journey_id FROM tbl_journeys WHERE identity='$driver_id' AND DATE_FORMAT(`date`, '%Y %m %d')='$today'";

I tried this way but it's not working. In the statement, date is a column in the table which I need to trim to only Year-month-day


Solution

  • You're using different characters between the year, month, and day in the two formats.

    $today=date("Y-m-d");
    

    puts hyphens between them, while

    DATE_FORMAT(`date`, '%Y %m %d')
    

    puts spaces between them.

    Change one of them to match the other, e.g.

    DATE_FORMAT(`date`, '%Y-%m-%d')
    

    Or you could just do it all in MySQL:

    $sql="SELECT journey_id FROM tbl_journeys 
          WHERE identity='$driver_id' AND DATE(`date`) = TODAY()";