mOna
mOna

Reputation: 2459

php mutiselect dropdown which get data from mysql

I would like to create a multi-select drop down list of countries in my form which lets users choose more than one country and also provides the ability to remove the item they selected, if needed.

I could create a drop down list which extracts the name of the countries from a mysql table, but it lets users only select one country. I searched a lot for multi-select drop down but none of the samples that I have found get data from mysql. They had only a few options which could easily write with option value like How to access the values selected in the multiselect dropdown list in PHP?

This is my code through which only one item can be selected:

<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('imdb');

$sql2 = "SELECT country FROM countries";
$result2 = mysql_query($sql2);

echo "<select name='country'>";
while ($row = mysql_fetch_array($result2)) {
    echo "<option value='" . $row['country'] . "'>" . $row['country'] . "</option>";
}
echo "</select>";
?>

Upvotes: 1

Views: 4278

Answers (1)

mOna
mOna

Reputation: 2459

Finally, I found what I was looking for. So I share it since might be useful for those with similar question.

First, as Marc said, I had to add multiple like below:

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

and this is the html line that I was searching for :

<option value="<?php echo $row['country'];?>"> <?php echo $row['country'];?> </option>

where country is the name of the related field in my database.

it might be worth saying that in order to insert the result in database (e.g table name = "test", field name = "q5":

<?php
mysql_connect("hostname", "user name", "user password") or die(mysql_error());
mysql_select_db("db name") or die(mysql_error());

$q5 = implode(',', $_POST['countrylist']);
 if(isset($_POST['submit']))
 {       
   $query="INSERT INTO test (q5) values ('". $q5 ."')";

    mysql_query($query) or die (mysql_error() );

   }
?>

It worked for me and hope will be useful for others.

Upvotes: 1

Related Questions