带有系统时间戳

时间:2017-04-06 05:55:27

标签: php mysql sql subquery

我正在为汽车共享企业创建一个Web应用程序和后端数据库。我想确保仅显示当前时间未保留的汽车的搜索结果。我输入了一个查询(如下),但我不确定它是否正确。我正在使用两种关系,预订和汽车。

Reservations(R_No, M_ID, VIN, A_Code, start_time, end_time)
Cars(VIN, make, model, year, P_address, r_fee)

这是一个有效的查询吗?如果没有,那会使它有效吗?

$sql = "SELECT make, model, year, P_address, r_fee, VIN 
                    FROM `Cars`, `Reservations`
                    WHERE (
                            (make LIKE %'$search'% ) or
                            (model LIKE %'$search'%) or
                            (year LIKE %'$search'%) or
                            (P_address LIKE %'$search'%) or
                            (r_fee LIKE %'$search'%) and
            (Cars.VIN != Reservations.VIN)
        AND (
            SELECT start_time, end_time
            FROM   Reservations
            WHERE  end_time <= SYSDATETIME() <= start_time));"

1 个答案:

答案 0 :(得分:0)

应该修改它以使用参数化查询,并且可以使用SQL注入。

$sql = "SELECT c.`make`, c.`model`, c.`year`, c.`P_address`, c.`r_fee`, c.`VIN`
    FROM `Cars` c
    LEFT JOIN `Reservations` r
    ON c.`VIN` = r.`VIN` AND TIMESTAMP BETWEEN r.`end_time` AND r.`start_time`
    WHERE (
            (c.`make` LIKE '%$search%' ) or
            (c.`model` LIKE '%$search%') or
            (c.`year` LIKE '%$search%') or
            (c.`P_address` LIKE '%$search%') or
            (c.`r_fee` LIKE '%$search%')
        )
        AND r.`id` IS NULL;";

这将返回当前没有预订的汽车列表。但是,您可能真的想延长开始和结束时间 因此你不会得到那些很快就会开始预订的汽车。