Reputation: 85
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);
}
Upvotes: 3
Views: 4352
Reputation: 7618
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!
Upvotes: 4
Reputation: 4523
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.
}
Upvotes: 0