In my database it is a table: tab_companies and a column company_phone (big integer) with defalut value set to NULL.
When somebody fill the form and will leave the phone number field empty Code Igniter should add a NULL value to the database, but instead I am having always value '0'.
public function add_company()
{
$data = array(
'company_short-name' => $this->input->post('company_short-name'),
'company_full-name' => $this->input->post('company_full-name'),
'company_phone' => $this->input->post('company_phone'),
'company_address' => $this->input->post('company_address'),
);
return $this->db->insert('tab_companies', $data);
}
What I am doing wrong?
you could do, set it to NULL
in case its empty, like:
$company_phone = $this->input->post('company_phone');
...
'company_phone' => (!empty($company_phone)) ? $company_phone : NULL,
...
I just found an automatic solution. You simply should extend CI_Input
class by overriding the post()
method.
Create a MY_Input
class in /application/core/MY_Input.php
class MY_Input extends CI_Input {
public function post($index = NULL, $xss_clean = NULL)
{
$value= $this->_fetch_from_array($_POST, $index, $xss_clean);
return $value === '' ? null : $value;
}
}
From now on, every empty POST
value will be converted to NULL
.
//empty to null로
function empty2null($v){
return empty($v) ? null : $v;
}
Based on Sudhir's answer above, I created a small helper function to simplify in my helper file:
function nullAllowedInput($name, $post = TRUE)
{
if($post)
return (empty($_POST["$name"])) ? NULL : get_instance()->input->post("$name", TRUE);
return (empty($_GET["$name"])) ? NULL : get_instance()->input->get("$name", TRUE);
}
Calling from a controller when necessary:
// POST
// load the helper file here or via autoload.php
$data = [
'name' => nullAllowedInput('name'),
'phone' => nullAllowedInput('phone')
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With