1

I'm working on a category section for stories submitted to my website. I have a html select going on in my html and I have that submitting to the database using codeigniter functions. It is submitting to the database, but there seems to be a small problem...the select is only grabbing the last value that is selected. I need to have all the values that are selected entered into the database so I can pull them out at a later date.

This is the html I am using.

<select multiple class="multi" name="wGenre">
                  <option value="Action/Adventure">Action/Adventure</option>                      <option value="Angst">Angst</option>
                  <option value="Crime">Crime</option>
</select>

and then this is what I have in my model.

$this->title = $this->input->post('wTitle');    
$this->genre = $this->input->post('wGenre');    
$this->db->insert('story_tbl', $this);

Now, I believe the problem is with my database. I originally set up the field as an enum, but that won't work because it's either one or the other selection and I need to have multiples. So then I tried it as a text field, and it's just not grabbing everything. To be honest I'm at a loss and in need of some help. :)

2 Answers 2

3

Firstly you need to make sure the select tag is named the array manner:

<select multiple="multiple" class="multi" name="wGenre[]">

Then To get all values of the multiple select you could do the following to save the values in an array!

$this->title = $this->input->post('wTitle');    
$select_vals = array();
foreach($this->input->post('wGenre') as $val){
    $val.' - '; // Used as a delimiter for later use
    array_push($select_vals, $val);
}
$this->genre = $select_vals;    
$this->db->insert('story_tbl', $this);
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately that didn't work. It seems that the foreach was not constructed properly. I tried switching the $select_vals $this->input->post('wGenre') to see if that would work. and it did, but it's still only saving the last value and not all the values
2

I ended up solving this without a foreach loop.

First of all, I was writting my html select tag wrong. For it to select multiple values you have to add both [] at the end of the class and a muti tag...like this.

<select multiple="multiple" class="multi" name="wGenre[]">

and then in the php it has to be json encoded to be placed in the database correctly...like this...

$this->genre = json_encode($this->input->post('wGenre'));   

Thank you for all your help! I hope this helps someone else in the future! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.