使用pg_execute,我不能使用now()或null值

时间:2011-01-14 17:20:19

标签: php postgresql pdo

我正在使用pg_prepare在PHP中准备我的SQL语句。当我尝试使用值pg_execute的{​​{1}}时,该函数将失败。同样,使用SQL关键字NULL时会失败。

代码:

now()

错误:

  

[pg_execute]:查询失败:错误:整数的输入语法无效:第49行的actions.php中的“NULL”

正常pg_prepare($connection, "insert_autosave", 'INSERT INTO autosave (category, editor, session_id, content, timeout, as_hook) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id'); $result = pg_execute($connection, "insert_autosave", array($category, $editor, $sid, $content, ($sto == "timeout" ? 'TRUE' : 'FALSE'), (is_numeric($asid) ? $asid : 'NULL'))); 有效。关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:2)

我记得你可以使用PHP的null常量:

$result = pg_execute($connection, "insert_autosave", array(
   $category, 
   $editor, 
   $sid, 
   $content, 
   ($sto == "timeout" ? 'TRUE' : 'FALSE'), 
   (is_numeric($asid) ? $asid : null)
));

这绝对不适用于SQL函数,但您必须事先在声明中嵌入这些函数:

pg_prepare(
   $connection, 
   "insert_autosave", 
   'INSERT INTO autosave (some_date) VALUES (NOW())'
);

答案 1 :(得分:2)

netcoder已经解释了如何处理NULL情况。也可以通过占位符传递now(),使用特殊日期/时间输入值“now”,“today”等。(See documentation for more info

pg_prepare(
   $connection, 
   "insert_autosave", 
   'INSERT INTO autosave (some_date) VALUES ($1)'
);
pg_execute($connection, "insert_autosave", array('now'));
pg_execute($connection, "insert_autosave", array('2010-01-14 20:24:43'));

如果对类型有任何歧义,您可以使用$1::timestamp

NB!切勿在{{1​​}}之类的直接SQL查询中使用此功能,因为在这种情况下,将在准备时解析和记住该值,并且即使它在不同的事务中,每次执行也将获得相同的时间。在这种情况下,'now'::timestamp是首选。

相关问题