0

I am using a multiple select box as shown below:

<select multiple="pages" id="pages" name="pages[]">
    <option value="Home Page">Home Page</option>
    <option value="Contact Us">Contact Us</option>
    <option value="Support">Support</option>
</select>

The list of pages is generated from another table in the database.

At the moment I am imploding $_POST['pages'] and storing the string in the database. What is a more efficient method of storing the selected values?

And finally how can I still display all of the pages (retrieved from another table in the database) and have the pages that user selected, selected in that multiple select box.

E.g. A user has selected Contact Us - when displaying all of the pages on the edit page, the Contact Us entry is highlighted (selected).

2 Answers 2

0

The normal is collapse all in an array and i think it's pretty good.

Here it is an example: http://www.onlinetools.org/tricks/using_multiple_select.php

0

There isn't much more of an efficient way of storing $_POST['pages'] into the database other than turning the attribute value into array locations.

$type = array("Home Page","Contact Us","Support");

To maintain the selected items (for a POST) using an array is perfect. For example:

if(isset($_POST['submit'])){
    echo "<select name=\"pages\" id=\"pages\" names=\"pages[]\">";
    foreach($t as $loc=>$type)
        echo "<option value=\"$loc\">$type</option>";
    echo "</select>";
}else{
    echo "<select name=\"pages\" id=\"pages\" names=\"pages[]\">";
     foreach($t as $loc=>$type)
        if($_POST['pages'] == $loc) //select that item
            echo "<option value=\"$loc\" selected=\"selected\">$type</option>";
        else
            echo "<option value=\"$loc\">$type</option>";
    echo "</select>":
}

Selecting the items based off of data from a database just replace in the if statement on line 9 $loc with the array location that you stored in the database.

5
  • For maximum portability, use just selected rather than selected="selected".
    – Barmar
    Aug 24, 2012 at 0:24
  • Yeah, that's what I usually do, but It's not valid HTML Aug 24, 2012 at 0:25
  • Yes it is. The HTML specification refers to this as the "minimized form", and mentions that many user agents only recognize this form. See w3.org/TR/html4/intro/sgmltut.html#h-3.3.4.2.
    – Barmar
    Aug 24, 2012 at 0:47
  • I am unable to get it working. The pages are stored in the database in this format Home Page,Contact Us,Support - I am unsure how to put them into an array $loc
    – Hammo
    Aug 24, 2012 at 1:56
  • @Hammo $loc references the index, you wouldn't put them into that array. Aug 24, 2012 at 3:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.