Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Insert Selected or All List/Menu items into Database

Posted on 2011-02-26
Medium Priority
Last Modified: 2012-05-11
I have a <div> that gets populated by the database.
            echo ("<select multiple size=22 name='Sel' class='full Sel' style='width:375px;')'>");
                $sitename = $row_Recordset1["Title"];
            echo ("<option value='$sitename'>$sitename</option>");
                while ($row = mysql_fetch_array($Recordset1)) {
                    $sitename = $row["Title"];
                    echo ("<option value='$sitename'>$sitename</option>");
            echo ("</select>")

This works great, I get the list I desire.  Now I would like people to be able to select what they wish and Add via a button, also an Add All button if desired to add what they select into a separate section of the database set aside for their use.

Any help on how I can do this?  Sometimes the list to choose from will be as little as 1 to more then 300 items depending on their choice.

I have another box to list what is displayed but I can get that once I get the items they select into the database.

Thank you in advance.
Question by:corterp
  • 2
LVL 18

Expert Comment

by:Sudaraka Wijesinghe
ID: 34990353
You can do this in several ways;

1. since you are already using a multiselect element, you can let the user select multiple items with holding Ctrl/Shift keys and post that to the server

2. or you can use a second select element and use some client side scripting to move items between the two selects, then you post the second multiselect to the server.

Note that in both cases you will have to name your multiselect with a name ending with [] to make the server side (PHP) treat it as an array (so you get all the selected items)
<select multiple size=22 name='Sel[]' class='full Sel' style='width:375px;'>

Open in new window

3. in addition to the above tow methods you can also use a widget like jQuery UI - multiselect to make it a bit fancy.
See the demo here

Author Comment

ID: 34990632
HI Sudaraka,

I am basically new to this.

This is what I have so far for the All All button.

<div id="AddAll">
  <form id="form1" name="form1" method="post" action="">
      <input type="button" name="AddAll" id="AddAll2" value="Add All" onClick="addall" />
<script type="text/javascript">
      function addall() {
      <?php $L1 = $_SESSION['SelM1']; ?>
        <?php if ($L1 != '') { ?>
                        $array = Sel;
                        foreach ( $array as $value ) {
                              mysql_query("INSERT INTO PL (PLTitle, PLItem)
                              VALUES ('$L1', '$value')");
            <?php } ?>

Nothing appears in the database and I fear adding when people select vice just clicking add all will be much more difficult.

Again thank you for your help.

LVL 18

Accepted Solution

Sudaraka Wijesinghe earned 2000 total points
ID: 34991523
It seems you have misunderstood the difference between server side and client side code.

The HTML form and the JavaScript part runs in the client side which is the web browser.
And the PHP part runs in the web server, apache or IIS or whatever you use to host the web site.

The way you have placed the PHP code, it executes well before your button is clicked and even before the page comes down to the browser.

I have created this sample code based on the scenario you explained, that I hope will help you to understand the concept.

Client side code (Form with select element and buttons + the select all JavaScript)
Client side HTML/JavaScript for displaying the form with multi-select input

You will need to make this page a .php when dynamixally generating the option list of the multi-select input

	<!-- Client side script for select all -->
	<script type="text/javascript">

	function selectAll(){
		var Form=document.getElementById('frmSelectDemo');
		var Sel=document.getElementById('Sel');

		if(Sel.options.length){ //Make sure there are one or more options in the select box

			for(var optionIndex=0; optionIndex < Sel.options.length; optionIndex++){ //Loop through each element
				Sel.options[optionIndex].selected=true; //Select each element


		//Submit the form to server side.

	<!-- Form element set to HTTP POST the selection to server side -->
	<form action="server-side.php" method="post" id="frmSelectDemo">

		<!-- Note: the name here is Sel[] so the server side (PHP) treat it as an array when posted -->
		<select multiple size=22 name='Sel[]' id="Sel" class='full Sel' style='width:375px;'>
		<option value="1">text 1</option>
		<option value="2">text 2</option>
		<option value="3">text 3</option>
		<option value="4">text 4</option>
		<option value="5">text 5</option>
		<option value="6">text 6</option>
		<option value="7">text 7</option>
		<option value="8">text 8</option>
		<option value="9">text 9</option>
		<option value="10">text 10</option>
		<option value="11">text 11</option>

		<input type="button" value="Select All &amp; Save To Database" onclick="selectAll();">
		<input type="submit" value="Save Selection To Database">

Open in new window

Server side code (capture the HTTP POST and save the values to DB)
 * Server side PHP script to populate the database with selected items sent to server side over HTTP POST

//Make sure we have a selection on HTTP POST and it is an array
if( isset($_POST['Sel']) && is_array($_POST['Sel']) ) //Note: we reffer to the selection as Sel (not Sel[])
	//We have the data, let's connect to the DB
	$db_handle = mysql_connect('localhost', 'root', '123') or die('MySQL database connection not available');

	mysql_select_db('test', $db_handle) or die('Database not available');

	 * Assume we are inserting to the following table
	 * CREATE TABLE `selection_store` (
	 * `selected_value` INT NULL)

	foreach ($_POST['Sel'] as $selected_value)
		$sql_statement = "insert into selection_store (selected_value) values (". mysql_real_escape_string($selected_value) .")";

		mysql_query($sql_statement, $db_handle);



Selected value(s) are inserted to the database. <br />
<a href="javascript:history.go(-1);">Go Back</a>

Open in new window


Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question