user2696666 user2696666 - 5 months ago 28
MySQL Question

if form field input is empty than do not update in database CODEIGNITOR

I have a form with 8 input fields. Now i don't want to update a field in the database if it's left empty. I saw some other post talking about it but i didn't find any good solution.

This are the fields that i like to check. if empty do not update them and leave the original value. whats the best way to do this? Thanks

This is my function in my controller

function update_profiel(){

$data = array(
'naam' => $this->input->post('naam'),
'email' => $this->input->post('email'),
'telefoon' => $this->input->post('telefoon'),
'gsm' => $this->input->post('gsm'),
'facebook' => $this->input->post('facebook'),
'twitter' => $this->input->post('twitter'),
'portfolio' => $this->input->post('portfolio'),
'profielfoto' => $this->input->post('browse')
);
$this->kdg_model->update_profiel($data);

}


My model

function update_profiel($data) {
$session_id = $this->session->userdata('user');
$this->db->where('user', $session_id);
$this->db->update('user', $data);

}

Answer

Just remove the field from your main array and check it in a different way.

Let's assume that this is your $data array:

$data = array(
    'naam' => $this->input->post('naam'),
    'email' => $this->input->post('email'),
    'telefoon' => $this->input->post('telefoon'),
    'gsm' => $this->input->post('gsm'),
    'facebook' => $this->input->post('facebook'),
    'twitter' => $this->input->post('twitter'),
    'portfolio' => $this->input->post('portfolio'),
    'profielfoto' => $this->input->post('browse')
); 

and about not_update_if_blank, all you need to do is check it after the $data array:

if( $this->input->post('not_update_if_blank') != "" )
{
    $data['not_update_if_blank'] = $this->input->post('not_update_if_blank');
}

now you can pass $data to your model.

EDIT:

$post_array = $this->input->post();
foreach( $post_array as $key=>$value )
{
    if(trim($value)!= "")
    {
       $data[$key] = $value;
    }
}

now pass $data to your model.
NB: test the code because I haven't tested it!

Comments