1

I'm using PDO prepared statements and obviously some fields may not be filled sometimes, so i get an integrity constraint violation error, How to make PDO to not look for null fields and just put the field on the db as it is?

P.S. They are even in TEXT type.

CodeOverload
  • 47,274
  • 54
  • 131
  • 219
  • 4
    I've managed to avoid PHP for more than a few years, so I don't know PDO very well, but an "integrity constraint violation error" sounds like "NOT NULL" is a requirement of the database, not of PDO. – Quentin Jan 28 '11 at 20:03
  • But why does it work when using a raw mysql function? – CodeOverload Jan 28 '11 at 20:34
  • Possible dupe: http://stackoverflow.com/questions/1391777/how-do-i-insert-null-values-using-pdo – Marc B Jan 28 '11 at 21:37

1 Answers1

2

Loop though them and remove the fields that are NULL before execution:

$fields = array(id=>3, name=>NULL, phone=>555-5555)
$attrinutes = array();

foreach ($fields as $field => $value) {
   if(isset($value)){
      $attributes[$field] = $value;
   }
}


$keys = array_keys($attributes);
$values = array_values($attributes);

$sql = "INSERT INTO ". static::$table_name ."(";
$sql .= implode(", ", $keys );
$sql .= ") VALUES (";
$sql .= implode( ", ", array_fill(0, count($attributes) ,'?' ) );
$sql .= ")";

$q = $this->connection->prepare($sql);
$q->execute($values);

*** NOT TESTED ***

Also make sure the fields are set to NULL in your DB

jwerre
  • 9,179
  • 9
  • 60
  • 69