无法获取当前日期的记录

时间:2018-12-18 09:00:37

标签: php mysql sql

我想基于当前日期从数据库中获取数据,在mysql中,使用NOW()可以正常工作,但是我尝试对php使用以下方式,但是它不起作用(它还会显示旧的日期数据)。 / p>

$date = date('Y-m-d');

$sql = "SELECT  a.created_date,a.shipment_id,o.order_id, o.customer_id,c.delivery_method
        FROM  `orders` AS o
        INNER JOIN  `table_1` AS a ON o.order_id = a.order_id
        INNER JOIN  `table_2` as c ON c.id=o.customer_id
        WHERE a.manifest_create_status =0 
            AND a.active_status=1 
            AND o.customer_id IN ($id)
            AND a.created_date > $date 
        ORDER BY a.created_date";

查询中有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您需要在日期值两边加上引号,例如a.created_date > '$date'

还请注意,表达式o.customer_id IN ($id)最好写成o.customer_id = $id

查询:

$sql = "SELECT  a.created_date,a.shipment_id,o.order_id, o.customer_id,c.delivery_method
        FROM  `orders` AS o
        INNER JOIN  `table_1` AS a ON o.order_id = a.order_id
        INNER JOIN  `table_2` as c ON c.id=o.customer_id
        WHERE a.manifest_create_status =0 
            AND a.active_status=1 
            AND o.customer_id = $id
            AND a.created_date > '$date' 
        ORDER BY a.created_date";

为避免此类问题,同时还提供针对任何类型的绑定注入的保护(id来自何处?),我建议如下使用绑定参数:

$date = date('Y-m-d');
$sql = "SELECT  a.created_date,a.shipment_id,o.order_id, o.customer_id,c.delivery_method
        FROM  `orders` AS o
        INNER JOIN  `table_1` AS a ON o.order_id = a.order_id
        INNER JOIN  `table_2` as c ON c.id=o.customer_id
        WHERE a.manifest_create_status =0 
            AND a.active_status=1 
            AND o.customer_id = ?
            AND a.created_date > ? 
        ORDER BY a.created_date";

$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $id, $date);
$stmt->execute();