Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当日期字段为空时,通过PHP将NULL插入PostgreSQL数据库_Php_Postgresql - Fatal编程技术网

当日期字段为空时,通过PHP将NULL插入PostgreSQL数据库

当日期字段为空时,通过PHP将NULL插入PostgreSQL数据库,php,postgresql,Php,Postgresql,我有一个csv数据集,其中包含一个日期字段,我的日期字段可能是空的,也可能不是空的(='')。我已经将Postgres设置为允许该字段为null,并为其指定了日期格式。当我运行PHP导入脚本(如下)时,导入失败,因为空字符串不是日期格式。我的理解是,我应该将其设置为NULL,只有当字段实际上为空时,我才想这样做。所以我想有条件地设置它,我认为它的工作原理如下: <?php if (empty($data[3])){ $data[3] = NULL;

我有一个csv数据集,其中包含一个日期字段,我的日期字段可能是空的,也可能不是空的
(='')
。我已经将Postgres设置为允许该字段为null,并为其指定了日期格式。当我运行PHP导入脚本(如下)时,导入失败,因为空字符串不是日期格式。我的理解是,我应该将其设置为
NULL
,只有当字段实际上为空时,我才想这样做。所以我想有条件地设置它,我认为它的工作原理如下:

    <?php if (empty($data[3])){
          $data[3] = NULL;
         // (i've tried "null", 'null', "NULL", null, etc.)

使用
$data[3]='null'
-null作为字符串,以便在查询中插入它时看起来像
null
,而不是

(虽然,你说你试过了……你确定你也犯了同样的错误吗?)


编辑:啊,仔细看看你的错误信息。您是否将数据库中的日期字段定义为“可能为空”值?请注意,我已经习惯MySQL,所以我可能在这方面错了。但无论如何,请尝试插入
'0000-00-00 00:00:00'
作为空日期的表示。

您的问题是SQL中有单引号:

INSERT INTO product (first_field, second_field, third_field, my_date) 
VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
# Warning: my PHP is a bit rusty but I think this is right
if(empty($data[0])) {
    $data[0] = "NULL";
}
else {
    $data[0] = "'" . pg_escape_string(utf8_encode($data[$c])) . "'";
}
因此,如果
$data[0]
是字符串
“NULL”
,那么您将得到以下结果:

INSERT INTO product (first_field, second_field, third_field, my_date) 
VALUES ('NULL', ...
您将尝试插入一个包含NULL而不是NULL文本本身的字符串。您必须在
$data
值中进行报价,而不是在SQL中进行报价:

INSERT INTO product (first_field, second_field, third_field, my_date) 
VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
# Warning: my PHP is a bit rusty but I think this is right
if(empty($data[0])) {
    $data[0] = "NULL";
}
else {
    $data[0] = "'" . pg_escape_string(utf8_encode($data[$c])) . "'";
}
后来:

pg_query($_db, "INSERT INTO product (first_field, second_field, third_field, my_date) 
    VALUES ($data[0], $data[1], $data[2], $data[3])";
或者更好,切换到并使用准备好的语句。

注意使用NULLIF()PostgreSQL函数

<?php
pg_query($_db, "INSERT INTO product (first_field, second_field, third_field, my_date) 
VALUES ('$data[0]', '$data[1]', '$data[2]', NULLIF('$data[3]', ''))";
?>

NULLIF的sintax是:NULLIF(“$emptysstring”,”):int。其中“::int”是相对的整数


我希望这对你有帮助。祝你好运。

我认为这是postgresql特有的东西,可能与之相关-因此最好使用预先准备好的语句,可能这样可以更清楚地知道是实际值造成了错误还是表定义错误。各种带引号的手段都没有帮助,但把一切都转到PDO和准备好的声明上,效果很好。谢谢