Get multiple values of checkbox in codeigniter

2019-05-28 10:56发布

问题:

I am currently doing a project. I have a checkbox( where the user will choose type of services provided by the company). When I try to post the service that was selected(for example 2 services is checked) in my controller, I am only getting one service. The question is how can I get the multiple values in my checkbox?

Note: I also tried to use foreach within my controller, I am getting some error like "Invalid argument supplied for foreach()".

View

<label>Desired Service</label> <br>
<?php foreach($services as $s):?>
<label><input type="checkbox" name="service_name[]" value="<?= $s->service_name?>"><?= $s->service_name?></label>
<br> 
<?php endforeach?>

Controller

$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
    $this->form_validation->set_rules('full_name', 'Fullname', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required');
    $this->form_validation->set_rules('contact', 'Contact', 'required');
    $this->form_validation->set_rules('date', 'Date', 'required');
    $this->form_validation->set_rules('address', 'Address', 'required');
    $this->form_validation->set_rules('zip_code', 'Zip Code', 'numeric|required');
    $this->form_validation->set_rules('province', 'Province', 'required');
    $this->form_validation->set_rules('date', 'Date', 'required');
    $this->form_validation->set_rules('service_name', 'Service', 'required');
    if ($this->form_validation->run() == FALSE) {
        $this->index();
    } 
    else {
        $service_name = implode(', ', $_POST['service_name']);
        $event = array(
        'full_name' => $this->input->post('full_name'),
        'email' => $this->input->post('email'),
        'contact' => $this->input->post('contact'),
        'address' => $this->input->post('address'),
        'zip_code' => $this->input->post('zip_code'),
        'state_province' => $this->input->post('province'),
        'date' => $this->input->post('date'),
        'service' => $service_name

        );
        $this->EventModel->add_event($event);
        echo "<script>
        window.alert('Your Desired Date is being Proccessed!');
        location.href = '".site_url('/')."';
        </script>";
    }

回答1:

Change from

$service_name = $_POST['service_name'];
foreach($service_name as $key =>$value)
{
    echo $value;
}
die;

to

$service_name = implode(',',$_POST['service_name']);
echo $service_name;


回答2:

I hope it will solve your problem

if (!empty($this->input->post('service_name'))) {
        foreach ($this->input->post('service_name') as $key => $val) {
            $data[] = array(
            'service_name' => $_POST['service_name'][$key]
        );
}
foreach ($data as $item) {    
       echo $item['service_name'];
}


回答3:

Try:

$service_name = $this->input->post('service_name');

for($i=0;$i < count($service_name);$i++){
    echo $service_name[$i];
}