Search code examples
phppostgresqlunix-timestamppg-query

unix second into postgres timestamp using php pg_query_params


I want to insert a unix timestamp value into a postgres timestamp column, using the PHP pg_query_params method, but get stuck.

Here's the incomplete code:

$con = pg_connect(...);
$stmt = 'INSERT INTO my_table (submitted) VALUES ($1)';
$ts = 1479939387;
$values = [translate_timestamp_into_sth_postgres_accepts($ts)];
$res = pg_query_params($con, $stmt, $values);

Q: how to transform the unix seconds value to sth. postgres accepts?


Solution

  • Use the function to_timestamp(double precision):

    select to_timestamp(1479939387) at time zone 'utc' as tstamp;
    
           tstamp        
    ---------------------
     2016-11-23 22:16:27
    (1 row)
    

    Your code may look like this (using default time zone):

    $con = pg_connect(...);
    $stmt = 'INSERT INTO my_table (submitted) VALUES (to_timestamp($1))';
    $ts = 1479939387;
    $res = pg_query_params($con, $stmt, $ts);