How to pass date as parameter from php to postgres

时间:2019-03-19 15:03:57

标签: php postgresql

i have the following request:

 select * from newagenda where 
     debut >'$1' AND debut < date '$1' + interval '24 hours' and
     agendaid=$2' 

which fails with a type cast error...

 failed: the error: = FEHLER: ungültige Eingabesyntax für Typ timestamp:

i try to translate: ERROR: invalid inputsyntax for type timestamp:

before i parametrized, i had

 select * from newagenda where debut >'$adate' AND debut < date '$adate' +
     interval '24 hours' and agendaid=$agid;

which worked perfectly well.....

now, the date comes back through a post request from a web request, so can inherently be manipulated, that's why would like to parametrize it, but i am clueless on how to get this to work.....

i tried

 select * from newagenda where 
     debut >'$1'::DATE AND debut < date '$1'::DATE + interval '24 hours' and
     agendaid=$2' 

or

$largs = array($isodate."::DATE");

also

$largs = array("'".$isodate."'::DATE");

but nothing worked...... how can i get this get to work? thanks in advance!

2 个答案:

答案 0 :(得分:0)

您可能正在寻找符合以下条件的东西:

<?php

//using single quoates to make sure the variables aren't expanded
$sql = 'select * from newagenda 
        where 
            debut >$1::DATE 
            AND debut < date $2::DATE
            and agendaid=$3';

$formattedDate = new \DateTime($date);
$rangeStart = $formattedDate->format('Y-m-d G:i:s');
$formattedDate->add('1 day');
$rangeEnd = $formattedDate->format('Y-m-d G:i:s');

pg_prepare($con,'sel_from_agenda', $sql);
pg_execute($con,'sel_from_agenda', [$rangeStart, $rangeEnd, $agid]);

我在这里使用功能连接,但最好使用OO或PDO。

答案 1 :(得分:0)

您可以使用pomm-project/foundation库来利用参数(和结果)转换器,并使用范围类型和运算符:

$pomm = new PommProject\Foundation\Pomm(['db' => ['dsn' => 'pgsql://user@host/db_name']]);

$date = new \Datetime(); // set your date here
$query = <<<SQL
select * from newagenda
where
  tsrange($*::timestamp, $*::timestamp + '1 day'::interval, '()') @> debut
  and agendaid = $*
SQL;
$iterator = $pomm['db']
    ->getQueryManager()
    ->query($query, [$date, $date, 123]);

foreach ($iterator as $row) {
    print_r($row);
}