I am new to CodeIgniter and working with arrays. I am trying to get the value of each check box into the same row in the database. I know I need to loop through the array, but then I am not sure how to tell it to write the values under their corresponding headings in the database. This is what I have tried but its writing 0 to the database for all options. Thanks to anyone taking the time to awnser my question.
//view
<input type="text" name="name" /> Name
<input type="checkbox" value="1" name="options[]" /> Option 1
<input type="checkbox" value="2" name="options[]" /> Option 2
<input type="checkbox" value="3" name="options[]" /> Option 3
<input type="checkbox" value="4" name="options[]" /> Option 4
//controller
//require at least 1 checkbox
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('options[]', 'Options', 'required');
//not sure how to do this part,
//some how get values to the corresponding "option"
$name = $this->input->post('name');
$option1 = $this->input->post('options[0]');
$option2 = $this->input->post('options[1]');
$option3 = $this->input->post('options[2]');
$option4 = $this->input->post('options[3]');
//insert to database
$this->load->model('add', 'add_model');
$this->add_model->create_person($name, $option1, $option2, $option3, $option4);
//database
| id | name | option1 | option2 | option3 | option4 |
I personally would have different named checkboxes and would validate by jQuery in the view before sending the form, but here’s the code that will point you in a right direction.
When you submit your form options array will have as many elements as you have selected on the form. If no checkbox has been selected the array would be empty so your code:
would be trying to get the third element of an empty array.
You need to loop through existing elements and assign those values to your variables.
You can do that by using this code:
The code above isn’t particularly elegant but I hope it will help you