first post at StackOverflow. I hope my question is good enough and well formulated.
I have a list of orders in my project with 3 dropdown menus, the dropdowns are for year, month and type of payment.
I'll just ask for one of them as the solution will be universal for them all.
For the month drop down, I have a list of all months (Jan-Dec) with values 01-12. I also have one option with the value 00, this option I want to represent all of the months, so if the user chooses this one the SQL query should ignore the AND MONTH() = value;
My SQL query I use is the following. This one is working as it should if all the strings are set to a value.
$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";
What i want to do is to replace the AND MONTH() with something like:
". $chosenmonth != '00' ? 'AND MONTH(date_added) = \'$chosenmonth\'' : '' ."
Thanks in advance!
UPDATE: I have now fixed the problem! Thank you Barmar for the assistance. I used echo to debug and finaly found a solution.. there is probably a nicer way to do this but this worked fine for me.
$chosenmonth = $_GET["month"];
$chosenyear = $_GET["year"];
$chosenpayment = $_GET["pay"];
$ifmonth = ($chosenmonth != NULL ? "AND MONTH(date_added) = '$chosenmonth' " : "");
$ifyear = ($chosenyear != NULL ? "AND YEAR(date_added) = '$chosenyear' " : "");
$ifpay = ($chosenpayment != NULL ? "AND oc_order.payment_code = '$chosenpayment' " : "");
$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)
". $ifmonth . $ifyear . $ifpay ."
ORDER BY orderID ASC";