Skip to main content
Have you ever tried to get multiple values from a single - selection/list box. It allows multiple selection with a simple attribute of multiple="multiple" but it does not work. The trick to make it work is use an array. How See below:


<html>
<head>
<title>The Form Page</title>
</head>
<body>
<p><strong>Form Page</strong></p>
<form name="per_info" method="post" action="insert.php">
<table width="64%" border="1" cellspacing="0" cellpadding="0">

<tr>
<td width="32%">Full Name: </td>
<td width="33%"><input type="text" name="fullname" /></td>
</tr>
<tr>
<td>E-Mail Address: </td>
<td><input type="text" name="email_add" /></td>
</tr>

<tr>
<td>Interests:</td>
<td><select name="interests[]" size="3" multiple="multiple">
<option value="Computers">Computers</option>
<option value="Technology">Technology</option>
<option value="Coding">Coding</option>
<option value="Photography">Photography</option>
<option value="Designing">Designing</option>
<option value="Gardening">Gardening</option>
<option value="DJing">DJing</option>
<option value="Other">Other</option>
</select></td>

<td width="35%"> <strong>*Use Ctrl Key to select Multiple Options</strong></td>

</tr>
<tr>
<td>&nbsp;</td>

<td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</form>

<p>&nbsp;</p>
</body>
</html>

Notice that interests[ ] the name of the select is an array.

Output:
Now it throws multiple selections from the same selection called interest to insert.php (refer above). So here we have a value like computerscoding.... as selected. The next way to separate the values is by using implode with a separator where I've used comma (,). Check the code below of insert.php



<?php
//code to connect to database with mysql_connect(required_parameters); or file include
$fn=$_POST['fullname'];
$eadd=$_POST['email_add'];

$interests_sent=$_POST['interests']; //sent from the form at form.php above page
$interests_to_db=implode(", ",$interests_sent); //add , after each separate value

//your insert into statement
?>

<head>

<title>Insert Page </title>

</head>

<body>

<? echo $interests_to_db; ?>

</body>
</html>
Output:

And you are done. A full example with a form and full insert code with a table in a database is available on mediafire. Its a 3 kb example so do download it and execute it after unzipping. This is how you get multiple values form a single select with PHP. Hope this example solved a problem of yours.

Geshan Manandhar

Comments