I have a csv data set containing a date field which my may or may not be empty (='')
. I've set Postgres to allow null on this field, and have given it the Date format. When I run my PHP import script (below), the import fails because the empty string is not in the date format. My understanding is that I should set it to NULL
, which I want to do only if the field is in fact empty. So I want to conditionally set it, which I thought would work like:
<?php if (empty($data[3])){
$data[3] = NULL;
// (i've tried "null", 'null', "NULL", null, etc.)
When I execute the import via this method, whenever the date field is empty, I get PHP Warning: pg_query(): Query failed: ERROR: invalid input syntax for type date: "NULL"
. Can PHP not pass NULL into a pg_query
? Should I be putting the conditional logic inside the query instead? My code is below. Thank you very much for any advice.
<?php
$conn_string = "host=localhost port=5432 dbname=mydb user=myusername password=mypassword";
$_db = pg_connect($conn_string);
$fileName = "../feeds/stale_prod_report.20111215.csv";
$row = 0;
if ($_db->connect_error) {
die('Connection Error (' . $_db->connect_errno . ') ' . $_db->connect_error);
}
if (($handle = fopen($fileName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$data[$c] = pg_escape_string(utf8_encode($data[$c]));
}
//if date is empty, insert a dummy - not accepting null
if (empty($data[16])){
$data[16] = NULL;
}
if($row !== 1){
pg_query($_db, "INSERT INTO product (first_field, second_field,
third_field, my_date)
VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]')";
}
fclose($handle);
} else {echo "Could not find the file!";}