3

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.

This are the fields that I like to check. if empty do not update them and leave the original value. How to do this?

This is my function in my controller

function update_profile(){

    $data = array(
            'name' => $this->input->post('name'),
            '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'),
            'profilefoto' => $this->input->post('browse')
            );
    $this->kdg_model->update_profile($data);
}

My model

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

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

ok works, but do i have to do this for every field in a separate if() or can i use a loop to get all fields in one time?
0

First of all the best solution near me is To Validate the form, but if you still want to avoid validation than go like this: Its the simplest way, not good but simplest:

E.g

if($name!='' && $email!='' && $facebook!='') //place all your Post variables here same like these 3 variables.
{

//Perform your Updation process here.

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.