Link to home
Start Free TrialLog in
Avatar of micro_learner
micro_learner

asked on

PHP how to set date value (mysql) to NULL

I have a mysql database where the inserted values are set to 0000-00-00 00:00:00 where I actually want NULL .I did the below but still get the date_value in the format 0000-00-00 00:00:00

    $this->fields['date_value'] =NULL;

    $insert_sql = "INSERT INTO {$this->table_name} ("
                . implode(",", array_keys($this->fields))
                . ") VALUES ('"
                . implode("','", array_values($this->fields))
                . "')";
Avatar of asianandrew
asianandrew
Flag of United States of America image

Check your field settings. Does it allow null?
Avatar of micro_learner
micro_learner

ASKER

Yes it does.
The default is NULL and allows null's.
 
I am confused :-(
 
I know this seems silly, but try:

$this->fields['date_value'] ="NULL";

As per http://bytes.com/groups/php/1146-insert-null-not-blank-into-mysql-php-script

I've had issues with not using double quotes before, so maybe this will work.
Even if you set the value to "NULL", it will be wrong here:

                . ") VALUES ('"
                . implode("','", array_values($this->fields))
                . "')";

All values gets quotes. You must change this. Maybe something like this:
foreach($this->fields as $key=>$value) {
  if($key=='date_value') $value = 'NULL';
  else $value = "'$value'";
}
 
$insert_sql = "INSERT INTO {$this->table_name} ("
                . implode(",", array_keys($this->fields))
                . ") VALUES ("
                . implode(",", array_values($this->fields))
                . ")";

Open in new window

Is there any bug in the above code because the Insertion fails ....
Avatar of Fugas
Could you post the the insert string here? Then you can use str_replace to replace 'null' with null without quotes, that should work.

This is mine ..which does not work (nulls are not eneterd)
 

 
 $this->fields['date_value'] =NULL;

$insert_sql = "INSERT INTO {$this->table_name} ("
. implode(",", array_keys($this->fields))
. ") VALUES ('"
. implode("','", array_values($this->fields))
. "')";
___________________________________
below si the one that I got in here in the above post ..but this returns an error (does not enter at all)
 
foreach($this->fields as $key=>$value) { if($key=='date_value') $value = 'NULL'; else $value = "'$value'"; }
 
$insert_sql = "INSERT INTO {$this->table_name} (" . implode(",", array_keys($this->fields)) . ") VALUES (" . implode(",", array_values($this->fields)) . ")";  
 
 
 ..how/where  do I use the str_replace function ? Thanks for all your help
ASKER CERTIFIED SOLUTION
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great