Solved

Insert Selected or All List/Menu items into Database

Posted on 2011-02-26
3
671 Views
Last Modified: 2012-05-11
I have a <div> that gets populated by the database.
      <?php
            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.
0
Comment
Question by:corterp
  • 2
3 Comments
 
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.
Samples:
http://www.mredkj.com/tutorials/tutorial_mixed2b.html
http://www.iknowkungfoo.com/blog/index.cfm/2008/6/6/Move-options-between-Select-Menus

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
0
 

Author Comment

by:corterp
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="">
    <label>
      <input type="button" name="AddAll" id="AddAll2" value="Add All" onClick="addall" />
    </label>
  </form>
</div>
<script type="text/javascript">
      function addall() {
      <?php $L1 = $_SESSION['SelM1']; ?>
        <?php if ($L1 != '') { ?>
                  <?php
                        $array = Sel;
                        foreach ( $array as $value ) {
                              mysql_query("INSERT INTO PL (PLTitle, PLItem)
                              VALUES ('$L1', '$value')");
                              mysql_query("COMMIT");
                        }
                  ?>
            <?php } ?>
            }            
</script>

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.

0
 
LVL 18

Accepted Solution

by:
Sudaraka Wijesinghe earned 500 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

 -->
<html>
<head>
	<!-- 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.submit();
	}

	</script>
</head>
<body>
	<!-- 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>
		</select>

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

Open in new window



Server side code (capture the HTTP POST and save the values to DB)
<?php
/*
 * 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` (
	 * `record_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
	 * `inserted_date_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ,
	 * `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);
	}

	mysql_close($db_handle);
}

?>

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

Open in new window

0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Someone recently asked me about how to display a progress indicator on a page while an iframe is loading. And I remember when I first came across this myself. It was a bit tricky to get my head around, but really, it's very simple. The most impor…
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now