john smith
john smith

Reputation: 605

multiple select form in php

I have the following in my HTML form, among with other inputs, like <input type="test" name="foo"></input> and others.

<select name="tags" multiple="multiple">
  <option selected="selected" value="hello">hello</option>
  <option selected="selected" value="world">word</option>
</select>

The problem is that when I am using

var_dump($_POST);

the tags returned is a string, and it contains only the last item in the select, like this:

string(5) "world"

Any help?

Upvotes: 1

Views: 357

Answers (4)

Wezy
Wezy

Reputation: 667

use name="tags[]" that way an array is passed

then you can use

if(isset($_POST['tags'])){
    foreach($_POST['tags'] AS $value){
        echo $value;
    }
}

In this case be sure to set method="post" in your form tag.

You can use selected="selected" without a problem

Upvotes: 0

Pascut
Pascut

Reputation: 3434

Your code should look like:

<select name="tags[]" multiple="multiple">
   <option selected="selected" value="hello">hello</option>
   <option value="world">word</option>
</select>

And please don't use selected="selected" for every option. Selected="selected" should be used only for one option, the option to be shown default! This is very important!

Upvotes: 0

Techie
Techie

Reputation: 45134

Try using below code. Name should be name="tags[]". If you name is like name="tags" it will only pass one value, if you want to pass multiple values you should name it as an array.

<select name="tags[]" multiple="multiple">
  <option selected="selected" value="hello">hello</option>
  <option selected="selected" value="world">word</option>
</select>

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29985

Your HTML should indicate that it's submitting an array :

<select name="tags[]" multiple="multiple">

(note the [])

Upvotes: 1

Related Questions