Reputation: 360
Just want to pass checkbox array values to mysql database table after submitting the form (table columns: id, fanta, cola, sprite) . Each value should be inserted in seperate field (i.e. without using implode/explode functions). The best solution will be just passing "1" (if selected ) or "0" (if not selected). Please help me :)
Here is My Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_example2 extends CI_Model {
function __construct()
{
//Call the Model constructor
parent::__construct();
}
public function did_add() {
$data = array(
'fanta' => $this->input->post('fanta'),
'cola' => $this->input->post('cola'),
'sprite' => $this->input->post('sprite'),
);
$query = $this->db->insert('table_example2', $data);
if ($query) {
return true;}
else {
return false;}
}
}
Here is My View:
<div >
<?php
$this->load->helper("form","file","html","url");
echo $message;
echo validation_errors();
echo form_open("example2/add");
echo form_label("Drink:<br>","type");
?>
<input type="checkbox" name="types[]" value="fanta" <?php echo set_checkbox('types[]', 'fanta', FALSE); ?>/>Fanta<br />
<input type="checkbox" name="types[]" value="cola" <?php echo set_checkbox('types[]', 'cola', FALSE); ?>/>Coca Cola<br />
<input type="checkbox" name="types[]" value="sprite" <?php echo set_checkbox('types[]', 'sprite', FALSE); ?>/>Sprite<br />
echo form_submit("Submit", "Add");
echo form_close();
</div>
Here is My Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Example2 extends MX_Controller {
public function add() {
$this->load->library('form_validation');
$this->load->model('model_example2');
$this->form_validation->set_rules('types[]', 'Drink','required');
if($this->form_validation->run()){
$this->model_example2->did_add();
$data["message"] = "Great job!";
$this->load->view("view_add_success",$data);
}
else {
$data["message"] = "";
$this->load->view("view_example2",$data);
}
}
}
Upvotes: 1
Views: 10905
Reputation: 446
You can try like this
public function did_add() {
$types = $this->input->post('types');
$data = array(
'fanta' => 0,
'cola' => 0,
'sprite' => 0,
);
foreach ($types as $type) {
$data[$type] = 1;
}
$query = $this->db->insert('table_example2', $data);
if ($query) {
return true;
}
else {
return false;
}
}
Upvotes: 2