开发者

php multiple select drop down

here is my mysql and php code layout:

I have 3 tables

  • tableA stores unique "person" information
  • tableB stores unique "places" information
  • tableC stores not unique information about a person and places they have "beenTo".

here is how i layed out my form: -on开发者_如何学JAVAe big form to insert into "person" tableA; "beenTo" tableC in the form, a person mulitple selects "places" which get inserted into "beenTo"

my question is, when i am editing a "person" how do i display what the user has already selected to appear on my multiple select options drop down menu?

my drop down menu at the moment query "places" table and displays it in a multiple select drop down menu. its easier when a person have beenTo one place, the problem arrises when there is more than one "beenTo" places?


Foreach option, check if they have beenTo it. Then add the selected="selected" attribute to the tag if true.

Example:

<select multiple="multiple">
    <option selected="selected">Rome</option>
    <option>France</option>
    <option selected="selected">Underpants</option>
</select>

And in PHP this might look like:

$beenTo = array("Rome","Underpants");
$places = array("Rome","France","Underpants");
?> <select multiple="multiple"> <?php
foreach($places as $place) {
    echo "<option";
    $found = false;
    foreach($beenTo as $placeBeenTo) {
        echo "value='$place'";
        if ($placeBeenTo == $place) {
            $found == true;
            echo " selected=\"selected\" ";
            break;
        }
    }
    if (!$found) echo ">";
    echo $place . "</option>";
}
?> </select> <?php

There's probably a much more efficient way to do this.


For clarification, you will want to have a name attribute for your select tag which allows for multiple selected options to function correctly.

<form method="post" action="">
<select name="places[]" multiple="multiple">
<?php
$_POST += array('places' => array());
$places = array('fr' => 'France', 'cn' => 'China', 'jp' => 'Japan');
$beenTo = array_flip($_POST['places']);
foreach ($places as $place => $place_label) {
  $selected = isset($beenTo[$place]) ? ' selected="selected"' : '';
  echo '<option value="' . $place . '"' . $selected . '>' . $place_label . '</option>';
}
?>
</select>
<input type="submit" value="Save Changes" />
</form>


<option id = 'example' <? if ($_POST['example']) echo 'selected' ?>>

But you'll be using a $_SERVER['cookies'] or other cache to store the past visits, not the $_POST array.. edit with extreme predjudice

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜