title: Insert NULL into a PostgreSQL DB via PHP when a date field is empty
body: <p>I have a csv data set containing a date field which my may or may not be empty <code>(='')</code>.  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 <code>NULL</code>, 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:</p>
  
  <pre><code>    &lt;?php if (empty($data[3])){
            $data[3] = NULL;
           // (i've tried "null", 'null', "NULL", null, etc.)
  </code></pre>
  
  <p>When I execute the import via this method, whenever the date field is empty, I get <code>PHP Warning:  pg_query(): Query failed: ERROR:  invalid input syntax for type date: "NULL"</code>.  Can PHP not pass NULL into a <code>pg_query</code>?  Should I be putting the conditional logic inside the query instead?  My code is below.  Thank you very much for any advice.</p>
  
  <pre><code>&lt;?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-&gt;connect_error) {
  die('Connection Error (' . $_db-&gt;connect_errno . ') ' . $_db-&gt;connect_error);
  }
  
  if (($handle = fopen($fileName, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      $num = count($data);
      $row++;
      for ($c=0; $c &lt; $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!";}
  </code></pre>