简体   繁体   中英

How to pass date as parameter from php to postgres

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!

You are probably looking for something along the lines of :

<?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]);

I using functional connections here but it would probably be best to use OO or PDO.

You can use the pomm-project/foundation library take advantage of the parameters (and results) converters and by the way use the range type and operators:

$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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM