Forum Moderators: coopster

Message Too Old, No Replies

save multiple id, in a field.

         

agxFalcon

1:40 am on Oct 23, 2009 (gmt 0)

10+ Year Member



Hello guys!

So i have this code:


$genre_list = array(1 => "Action", 2 => "Adventure", 3 => "Comedy", 4 => "Dementia", 5 => "Demons", 6 => "Drama", 7 => "Fantasy", 8 => "Horror");


<select name='genre' multiple='multiple' class='multiple' size='8'>
foreach ($genre_list as $genre_id=>$genre_name) {
<option value='".$genre_id."'>$genre_name</option>
}
</select>

The thing is, that is saving just the last selected genre_name, how do i fix this problem ?

omoutop

5:59 am on Oct 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



you can only select 1 value from a select list
you can use some javascript to allow multiple selections
or use checkboxes instead

rocknbil

4:56 pm on Oct 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome aboard agxFalcon!


you can only select 1 value from a select list

Oops! :-)

multiple='multiple'

The trick is with PHP, you need to add [] by the name so it's an array.

name="genre[]"

Tested and working, slight changes because I prefer double-quotes on output HTML attributes . . . matter of preference.


<?php
header("content-type:text/html");
$genre_list = array(
1 => "Action",
2 => "Adventure",
3 => "Comedy",
4 => "Dementia",
5 => "Demons",
6 => "Drama",
7 => "Fantasy",
8 => "Horror"
);
if (isset($_POST['genre'])) {
$genres = $_POST['genre'];
foreach ($genres as $g){
$form .= "<p>You selected " . $genre_list[$g] . ", key $g</p>";
};
}
else {
$form = '
<form method="post" action="multiple-selects.php">
<select name="genre[]" multiple="multiple" class="multiple" size="8">
';
foreach ($genre_list as $genre_id=>$genre_name) {
$form .= '<option value="'.$genre_id.'">'.$genre_name.'</option>';
}
$form .= '
</select>
<input type="submit" value="Test It">
</form>
';
}
echo $form;
?>