Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Date time format in SQL query

Tags:

sql

php

I'm doing my analysis code which will show sales report from 7 from now.

Here is my full code:

<?php
include 'report/go.php';

$to_time =time();
$to_time = date("Y-m-d H:i:s",$to_time);
$from_time = time()-6*60*60;
$from_time = date("Y-m-d H:i:s",$from_time);


    $sql = "SELECT 
            *
            FROM Tickets
            WHERE LastUpdateTime BETWEEN $from_time and $to_time";

    $stmt = sqlsrv_query( $conn, $sql );
        if( $stmt === false) {
            die( print_r( sqlsrv_errors(), true) );
        }
        while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
                $Date = $row['LastUpdateTime']->format('d/m/Y');
                $Time = $row['LastUpdateTime']->format('H:i:s');
                $Hour = $row['LastUpdateTime']->format('H');
            echo $row['Id']." - ".$Date." - ".$Time." - ".$Hour." Total amount: ".floor($row['TotalAmount'])."<br />";
        }

sqlsrv_free_stmt( $stmt);
?>

My code doesn't work. I believe I've got some problems with date time convert or that kind of thing. Can anyone help me?

like image 629
Anthony L. Avatar asked Mar 15 '16 06:03

Anthony L.


Video Answer


1 Answers

datetime should be wrapped in 's as they are strings.

"SELECT 
*
FROM Tickets
WHERE LastUpdateTime BETWEEN '$from_time' and '$to_time'"

And for calculating the $from_time you can do only -

$from_time = date("Y-m-d H:i:s", strtotime('- 6 HOURS'));

instead of

$from_time = time()-6*60*60;
$from_time = date("Y-m-d H:i:s",$from_time);
like image 66
Sougata Bose Avatar answered Oct 13 '22 19:10

Sougata Bose