问题
I have a query that I am trying to set up entirely from bound parameters, but right now I'm having to resort to appending a string from a GET parameter (I don't really want to do that).
Here's my solution right now:
$interval = !empty($_REQUEST['interval']) ? $_REQUEST['interval'] : '28 DAY';
$interval = str_replace('_', ' ', $interval);
$data = array(
':msisdn' => $_REQUEST['msisdn']
);
$sql = <<<SQL
SELECT
COUNT(*) AS `countup`
FROM
(
SELECT
utc.`id_user`
FROM
`user_to_cli` utc
WHERE
1=1
AND utc.`cli` = :msisdn
AND utc.`dts_start` > CURDATE() - INTERVAL $interval
) a
;
SQL;
This works fine, but when I try to change the interval to a bound parameter, like so:
$interval = !empty($_REQUEST['interval']) ? $_REQUEST['interval'] : '28 DAY';
$interval = str_replace('_', ' ', $interval);
$data = array(
':msisdn' => $_REQUEST['msisdn'],
':interval' => $interval
);
$sql = <<<SQL
SELECT
COUNT(*) AS `countup`
FROM
(
SELECT
*
FROM
`user_to_cli` utc
WHERE
1=1
AND utc.`cli` = :msisdn
AND utc.`dts_start` > CURDATE() - INTERVAL :interval
) a
;
SQL;
I get the following error:
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') a'
回答1:
Your code tries to use a bind variable to replace a SQL keyword as well as a number. You Can't Do That™.
When I've solved this problem I've translated my time intervals to seconds then used
CURDATE() - INTERVAL :seconds SECONDS
By the way, CURDATE() gives you midnight today. You may want NOW() instead if you're handling sub-day intervals.
来源:https://stackoverflow.com/questions/54128115/how-do-i-bind-an-interval-param-with-pdo