Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Find out what you should include to make the best professional email signature for your organization.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

715 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