Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind an INTERVAL param with PDO?

Tags:

php

mysql

pdo

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'
like image 539
Elliott Rhys Avatar asked Aug 27 '26 00:08

Elliott Rhys


1 Answers

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.

like image 181
O. Jones Avatar answered Aug 29 '26 14:08

O. Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!