Gold Apple Software Web Development by Geoff Appleby

Storing NULL values to database in CakePHP

After searching for a while, I was unable to find information on how to make sure CakePHP will store a NULL value to the database. If you unset the value from the data array sent to saveAll(), it will not be changed from its current value: this will suffice for saving new rows to the database if their default value is NULL, but it will not overwrite an existing value with NULL.

The solution is simple, just not described well: set the value of the data array item to null. 

The following code snippet is from an instance where a user clears the value from a text field in order to remove the data.  If unchanged an empty string would be stored instead of the desired NULL value (and would later cause errors due to a UNIQUE key constraint).

if (empty($data['Model']['item']) {
  $data['Model']['item'] = null;
}
$this->Model->saveAll($data);

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <br> <p>
  • Lines and paragraphs break automatically.
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.