在SQL查询中使用PHP来确定查询的下一部分应该如何

时间:2016-04-14 20:11:00

标签: php mysql

StackOverflow的第一篇文章。我希望我的问题足够好并且制定得很好。

我的项目中有一个包含3个下拉菜单的订单列表,下拉列表是年,月和付款类型。

我只会问其中一个,因为解决方案对所有人都是普遍的。

对于月份下拉菜单,我列出了所有月份(1月至12月),值为01-12。我也有一个值为00的选项,这个选项我想表示所有月份,所以如果用户选择这个,SQL查询应该忽略AND MONTH()=值;

我使用的SQL查询如下。如果所有字符串都设置为值,那么这个应该正常工作。

/**
 * @expectedException ParseError
 */
public function testParseErrorLogsAnError()
{
    eval('<?php not good');
}

我想要做的是用以下内容替换AND MONTH():

$sql = "SELECT      oc_order.order_id AS orderID,               
                oc_order.firstname AS firstname,
                oc_order.lastname AS lastname,
                oc_order.payment_code AS paycode,
                oc_order.order_status_id AS statusID,
                oc_order.total AS totalsumma,
                oc_order.date_added AS date

    FROM        oc_order

    WHERE       (oc_order.order_status_id = 5 OR oc_order.order_status_id = 31)

    AND         MONTH(date_added) = '$chosenmonth'
    AND         YEAR(date_added) = '$chosenyear'
    AND         oc_order.payment_code = '$chosenpayway'

    ORDER BY orderID ASC";

提前致谢!

更新: 我现在已经解决了这个问题!谢谢Barmar的帮助。我使用echo进行调试并最终找到了解决方案..可能有更好的方法可以做到这一点但这对我来说很好。

". $chosenmonth != '00' ? 'AND MONTH(date_added) = \'$chosenmonth\'' : '' ."

1 个答案:

答案 0 :(得分:0)

你需要围绕三元表达式使用括​​号,因为默认优先级是以不同的方式组合事物。

$sql = "SELECT  oc_order.order_id AS orderID,               
                oc_order.firstname AS firstname,
                oc_order.lastname AS lastname,
                oc_order.payment_code AS paycode,
                oc_order.order_status_id AS statusID,
                oc_order.total AS totalsumma,
                oc_order.date_added AS date

    FROM        oc_order

    WHERE       (oc_order.order_status_id = 5 OR oc_order.order_status_id = 31)

    ". ($chosenmonth != '00' ? "AND MONTH(date_added) = '$chosenmonth'" : "") ."
    AND         YEAR(date_added) = '$chosenyear'
    AND         oc_order.payment_code = '$chosenpayway'

    ORDER BY orderID ASC";

如果你在一个单独的陈述中做了有条件的话,那么理解会更容易,而且错误也会更少。

$monthcheck = $chosenmonth != '00' ? "AND MONTH(date_added) = '$chosenmonth'" : "";

$sql = "SELECT  oc_order.order_id AS orderID,               
                oc_order.firstname AS firstname,
                oc_order.lastname AS lastname,
                oc_order.payment_code AS paycode,
                oc_order.order_status_id AS statusID,
                oc_order.total AS totalsumma,
                oc_order.date_added AS date

    FROM        oc_order

    WHERE       (oc_order.order_status_id = 5 OR oc_order.order_status_id = 31)
    $monthcheck
    AND         YEAR(date_added) = '$chosenyear'
    AND         oc_order.payment_code = '$chosenpayway'

    ORDER BY orderID ASC";