【问题标题】:Using pg_execute, I can't use now() or null values使用 pg_execute,我不能使用 now() 或 null 值
【发布时间】:2011-01-14 17:20:18
【问题描述】:

我正在使用pg_prepare 在 PHP 中准备我的 SQL 语句。当我尝试使用需要为NULL 的值来pg_execute 时,函数失败。同样,使用SQL关键字now()时也会失败。

代码:

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')));

错误:

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

做一个普通的pg_query 工作。关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: php postgresql pdo


    【解决方案1】:

    我记得你可以使用 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())'
    );
    

    【讨论】:

      【解决方案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

      注意!永远不要在像'now'::timestamp 这样的直接 SQL 查询中使用此功能,因为在这种情况下,值将在准备时被解析和记住,并且每次执行都将获得相同的时间,即使它在不同的事务中。在这种情况下,NOW() 是首选。

      【讨论】:

      • 我接受了另一个答案,因为null 问题是更紧迫的问题,它对我有用。但是,您的 now 解决方案也适用于现在的问题。谢谢!
      • 我们都是对的 :) 您不能使用 PDO 参数传递 SQL 函数。幸运的是,Postgres(与 MySQL 不同)对于 NOW 有一个特殊的 输入值(不是函数),我忘记了。为你 +1。
      猜你喜欢
      • 2013-08-03
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2015-11-19
      • 2020-04-05
      • 2021-08-22
      • 2016-12-17
      相关资源
      最近更新 更多