The proper way to insert a NULL into a database with CodeIgniter The proper way to insert a NULL into a database with CodeIgniter codeigniter codeigniter

The proper way to insert a NULL into a database with CodeIgniter


Assuming your variable is named $myvar AND assuming you've done all the error checking, validation and casting before this.

$myvar  = empty($myvar) ? NULL : $myvar;

This will give the correct data to codeignitor.


There's two ways of solving the issue aforementioned.

Firstly, you can just change the database (assuming you're using MySQL) field from "NOT NULL" to "NULL" so empty strings are automatically converted to a NULL by MySQL and would require no change from your code.

Secondly, you can run a query to tell CodeIgniter to null the string as such

$r = ($this->input->post('r') != FALSE) ? $this->input->post('r') : NULL;

If you're going to need the 'null' function more often, consider creating a library or helper within CodeIgniter with the code above in the form of a function.


This worked for me :) I assigned double single quotes string whenever the input value is NULL or empty

for($x = 0 ; $x < $count ; $x++) {    foreach(array_keys($_POST) as $col) {        $data[$this->col_prefix.$col] = empty($_POST[$col][$x]) ? "''" :  $_POST[$col][$x];    }    if($this->transaction_detail_model->add_transaction_detail($data)) {        $flash_data = array('status' => 1, 'message'=> 'Transaction successful saved!');    }   }