Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - how to post value from form as NULL instead of 0

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?

like image 694
Tikky Avatar asked Jun 26 '14 07:06

Tikky


4 Answers

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,
...
like image 55
Sudhir Bastakoti Avatar answered Nov 12 '22 12:11

Sudhir Bastakoti


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.

like image 32
b126 Avatar answered Nov 12 '22 11:11

b126


//empty to null로
function empty2null($v){
    return empty($v) ? null : $v;
}
like image 2
apeach Avatar answered Nov 12 '22 13:11

apeach


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')
];
like image 1
Sarvap Praharanayuthan Avatar answered Nov 12 '22 11:11

Sarvap Praharanayuthan