我正在使用OpenCart,我正在尝试更改此查询。我需要更改它以便它返回去年(从现在起1年)的记录,这是我的查询
$query = $this->db->query("SELECT count(*) AS total, channel FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$customer_id . "' && order_status_id IN(" . implode(",", $implode) . ") AND YEAR(date_added) = YEAR(CURDATE()) GROUP BY channel");
我尝试将其更改为此,但它的工作正在进行中:
$query = $this->db->query("SELECT count(*) AS total, channel FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$customer_id . "' && order_status_id IN(" . implode(",", $implode) . ") AND date_added BETWEEN CURDATE() - INTERVAL 1 year AND CURDATE()) GROUP BY channel");
答案 0 :(得分:0)
之前,请考虑清理输入数据以保护您的查询免受SQL注入。 Here您可以找到有关此主题的一些内容。
基于this answer,我们可以使您的PHP代码适应以下内容:
$query = $this->db->query("SELECT count(*) AS total, channel
FROM `" . DB_PREFIX . "order`
WHERE customer_id = '" . (int)$customer_id . "'
AND order_status_id IN(" . implode(",", $implode) . ")
AND date_added >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
GROUP BY channel");
答案 1 :(得分:0)
计算去年时语法错误。
您可以使用DATE_SUB。
$query = $this->db->query("SELECT count(*) AS total, channel FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$customer_id . "' && order_status_id IN(" . implode(",", $implode) . ") AND date_added BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND CURDATE()) GROUP BY channel");