1

How can I get the value of a multiple select input field in CodeIgniter controller?

I want a multiple select input field shown here

I have added below html code.

<select class="js-example-basic-multiple  multiple_selection form-control" name="student[]" multiple="multiple"  >
                <option value="1">Student1</option>
                <option value="2">Student2</option>
                <option value="3">Student3</option>
                <option value="4">Student4</option>
                <option value="5">Student5</option>
                <option value="6">Student6</option>
              </select>

I am using given code to fetch the value of this input field. But I didn't get the value.

$studentname = array();
    $studentname =$this->input->post('student[]');
    echo 'studentName:'.$studentname;

Do you have any suggestions?

Arya
  • 41
  • 1
  • 4
  • Possible duplicate of [How to get multiple selected values of select box in php?](https://stackoverflow.com/questions/2407284/how-to-get-multiple-selected-values-of-select-box-in-php) – Philipp Maurer Nov 28 '17 at 16:12

3 Answers3

2

Your values will be posted in an array:

$studentNames = $this->input->post('student');

You can then access each value using loop:

foreach($studentNames as $name){
    echo "Student name is $name";
}
Kisaragi
  • 2,198
  • 3
  • 16
  • 28
  • I have tried this method. I didn't get it. So I posted this question. – Arya Nov 28 '17 at 16:11
  • The trick is, that you use the name attribute `student[]` like in your code example and use it woithout the brackets in your code when retrieving it, like shown by Kisaragi. – Philipp Maurer Nov 28 '17 at 16:13
0

there is no need to use [] while you are echoing post value, you already define in name='student[]';

 $studentname =$this->input->post('student');
    echo "<pre>";
    print_r($studentname);
    echo "</pre>";
jvk
  • 2,133
  • 3
  • 19
  • 28
0

for naming sake make it student students since its a multislect

<select class="js-example-basic-multiple  multiple_selection form-control" name="students[]" multiple="multiple"  >
    <option value="1">Student1</option>
    <option value="2">Student2</option>
    <option value="3">Student3</option>
    <option value="4">Student4</option>
    <option value="5">Student5</option>
    <option value="6">Student6</option>
 </select>

in controller:

//get the post values of students (if you dump the post you will see that $_POST['students'] is an array
$students = $this->input->post('students');

https://www.codeigniter.com/user_guide/libraries/input.html

//will contain the values of the selected students ex. var_dump($students) will produce [1,2,4];

//you will need to loop over students since it is an array

foreach($students as $id){
  echo "Student id is {$id}";
}
Parker Dell
  • 472
  • 4
  • 11