如何在PHP PDO查询中插入“now()-interval”2分钟“等内容?

时间:2013-01-22 18:43:10

标签: php postgresql pdo

我有这样的查询:(在Postgresql 8.4,PHP-fpm 5.3.10(fpm-fcgi))

select * from users where now() - interval '2 minutes' < seenlast ORDER BY seenlast;

我想使用PHP / PDO查询,所以:

$mymin=5; //this is a variable can be changed by $_GET
$query = $db_conn->prepare("select * from users where now() - interval ':myminute minutes' < seenlast ORDER BY seenlast"); 
$query->bindParm(":myminute",$mymin)
$query->execute;

这不起作用,我找不到以合适的方式传递分钟( $ mymin )的方法。如果我硬编码时间作品,那么代码的其他部分必须是正确的。

我也尝试过:

$temp=$mymin." minutes";
$query = $db_conn->prepare("select * from users where now() - interval :myminute < seenlast ORDER BY seenlast"); 
$query->bindParm(":myminute",$temp)

I already saw this, didn't help

4 个答案:

答案 0 :(得分:15)

间隔可以乘以数字。因此,一种方法是准备语句interval '1 minute' * :myminutes,而不是将“myminutes”参数作为简单整数传递。

答案 1 :(得分:5)

我不太了解PDO或PHP,但我想我知道这里出了什么问题。

当你这样说时:

interval '3 minutes'

你真的在执行与以下相同的演员操作:

'3 minutes'::interval
cast('3 minutes' as interval)

所以你正在做的是将一个TEXT值转换为INTERVAL。这意味着您需要生成类似于字符串'3 minutes'的内容。您可以使用字符串连接将字符串片段粘贴在一起:

# Use cast to make the precedence cleaner.
$query = $db_conn->prepare("select * from users where now() - cast(:myminute || ' minutes' as interval) < seenlast ORDER BY seenlast"); 
$query->bindParm(":myminute", $mymin)

或者你应该能够在PHP中进行字符串争论:

$query = $db_conn->prepare("select * from users where now() - interval :myminute < seenlast ORDER BY seenlast"); 
$query->bindParm(":myminute", $mymin . ' minutes')

答案 2 :(得分:0)

我一直在与Phalcon及其内部模型PDO解析器争吵几个小时同样的问题。

我找到了这个解决方案:

public static function getTimedoutRequests($secsThreshold) {
    return self::find(
        array(
            // PDO is buggy here, can't use INTERVAL
            "DATE_PART('epoch', create_time) < DATE_PART('epoch', NOW()) - ?0",
            "bind" => array(
                $secsThreshold
            )
        )
    );
}

答案 3 :(得分:-2)

... - INTERVAL :myminute MINUTES ...
没有引号的

是正确的方法。如果有帮助,可以将占位符视为使用基于旧式变量的查询构建方法的等价物

... - INTERVAL $myminute MINUTES

除了占位符处理变量没有的注入漏洞。仅仅因为你使用占位符并不意味着你可以改变SQL语法,所以

... - INTERVAL '2 minutes'
... - INTERVAL ':myminute minute'

无效的SQL。


跟随mu:

mysql> select now() + interval '2 minute';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
mysql> select now() + interval 2 minute;
+---------------------------+
| now() + interval 2 minute |
+---------------------------+
| 2013-01-22 13:38:24       |
+---------------------------+
1 row in set (0.02 sec)