How to insert things like “now() -interval '2 minutes'” into PHP PDO query?

后端 未结 4 1194
无人共我
无人共我 2021-01-11 20:14

I have a query like this: (on Postgresql 8.4, PHP-fpm 5.3.10 (fpm-fcgi))

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


        
4条回答
  •  不知归路
    2021-01-11 20:45

    I don't know much PDO or PHP but I think I know what's going wrong here.

    When you say this:

    interval '3 minutes'
    

    You're really performing a cast operation that's the same as:

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

    So what you're doing is casting a TEXT value to an INTERVAL. That means that you need to produce something that looks like the string '3 minutes'. You could paste the string pieces together using string concatenation:

    # 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)
    

    Or you should be able to do the string wrangling in PHP:

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

提交回复
热议问题