Solved

How to create a multiple select drop down in php

Posted on 2013-12-13
9
1,101 Views
Last Modified: 2013-12-13
Hi all.

I currently have a drop down list where the end user selects 1 workschedule and then clicks the submit button and it gets inserted into a table. Now we want to be able to select multiple workschedules instead of just 1 and have all of those inserted into the table.

How can I do this?

Here is a condensed version of the 2 files:

Scheduling.php:

<?php 
     session 
   require("common.php");
       
    if (isset($_SESSION['user'])){   // check session
     
      if (isset($_POST)) {  //This if statement checks to determine whether the form has been submitted, If it has, then the code is run, otherwise the form is displayed  
           if (isset($_POST['action_token1']) && isset($_SESSION['action_token1']) && $_POST['action_token1'] == $_SESSION['action_token1']) {      // check request token               
           
            $query = "SELECT workscheduletypeid, workscheduledescription FROM WorkScheduleType WHERE workscheduletypeid NOT IN (SELECT workscheduletypeid FROM WorkScheduleDataEntry WHERE DataEntryID = :dataentryid) ";
        
            $query_params = array( 
            ':dataentryid' => $_POST['DataEntryID'] 
            );   
     
            $stmt = $db1->prepare($query); 
            $result = $stmt->execute($query_params); 
            $data1 = $stmt->fetchAll();  
            
            $_SESSION['DataEntryID'] = $_POST['DataEntryID'];
       // unset the form token session variable 
          unset( $_SESSION['action_token1'] );
        
       }    // Close check request token
      
       else {        // possible CSRF attempt 
            echo 'invalid submission'; 
            trigger_error('possible CSRF attack', E_USER_ERROR);    
            exit; 
        } 
      
      }  // Close isset($POST) if statement    
    } // Close check session
    
  $_SESSION['action_token1'] = generate_secure_token(); 
?> 

<!DOCTYPE html>
<head>
  <title>MyPage</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="style.css" type="text/css" />
  <link href="iphone-icon1.png" rel="apple-touch-icon">
   </script>
  </head>
<body>
      				
<div class="wrapper">
    <div id="logo"></div>
    <form class="form4" action="ProcessWorkSchedule_PM.php" method="post">
<div class="formtitle4">Slab/Dried In Lookup Form</div>

        	               
               
<div class="input nobottomborder">
                 <div class="inputtext">New Work:</div>
                 
                     <div class="inputcontent" ><select name="WorkSchedule"  id="WorkSchedule" style="width: 225px"><option selected="selected"></option>    
                
                <?php foreach($data1 as $row) { printf("<option value='%s'>%s</option>", html_escape($row['workscheduletypeid']), html_escape($row['workscheduledescription'])); }?>
                 	</select></div>  
   
            </div>       
             
            
        <input type="hidden" name="action_token1" value="<?php echo html_escape($_SESSION['action_token1']) ?>" />
 
       <?php  foreach ($data as $row){
        echo' <input type="hidden" input name = "DataEntryID" input id = "DataEntryID" value="' . html_escape($row['DataEntryID']) . '">';
        echo' <input type="hidden" input name = "BuilderCommunityID" input id = "BuilderCommunityID" value="' . html_escape($row['BuilderCommunityID']) . '">';              
        echo' <input type="hidden" input name = "type" input id = "type" value="' . html_escape($row['Type']) . '">';              
          
         }?>
<input class="button9"  type="submit" value="Assign Work" /> 
</form>
</body>
</html>

Open in new window


ProcessWorkSchedule_PM.php:
<?php 
    // First we execute our common code to connection to the database and start the session 
   require("common.php");
   require("class.phpmailer.php");
       
    if (isset($_SESSION['user'])){   // check session
     
      if (isset($_POST)) {  //This if statement checks to determine whether the form has been submitted, If it has, then the code is run, otherwise the form is displayed  
           if (isset($_POST['action_token1']) && isset($_SESSION['action_token1']) && $_POST['action_token1'] == $_SESSION['action_token1']) {      // check request token

$date = new DateTime();
          $date->setTimezone(new DateTimeZone('America/New_York'));
          $fdate = $date->format('Y-m-d H:i:s');

 $query = " 
            INSERT INTO WorkScheduleDataEntry ( 
                DataEntryID, 
                workscheduletypeid, 
                UserID,
                CreateDate
            ) VALUES ( 
                :dataentryid, 
                :workscheduletypeid, 
                :userid,
                :currentdatetime
            ) 
        "; 

                
        // Here we prepare our tokens for insertion into the SQL query.  
        $query_params = array( 
            ':dataentryid' => $_POST['DataEntryID'], 
            ':workscheduletypeid' => $_POST['WorkSchedule'], 
            ':userid' => $_SESSION['user']['userid'],
            ':currentdatetime' => $fdate
        ); 
                      
            // Execute the query to insert data into the WorkScheduleDataEntry table 
            $stmt = $db3->prepare($query); 
            $result = $stmt->execute($query_params); 
 unset( $_SESSION['action_token1'] );
        header('Location: WorkScheduleResults_PM.php');
        exit();
       
 
       }    // Close check request token
      
       else {        // possible CSRF attempt 
            echo 'invalid submission'; 
            trigger_error('possible CSRF attack', E_USER_ERROR);    
            exit; 
        } 
      
      }  // Close isset($POST) if statement    
    } // Close check session
    
 
 
?> 

Open in new window

0
Comment
Question by:Sim1980
  • 4
  • 3
  • 2
9 Comments
 
LVL 11

Expert Comment

by:N R
ID: 39717475
You want to select multiple items from the drop down box?  Don't know that's possible in a standard select box.

Would you be open to check boxes?
0
 

Author Comment

by:Sim1980
ID: 39717480
If that's the only way to be able to select multiple entries, how about a list box?
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39717483
I think you can make multiple selections in a select/option.  The selections become an array in the named input control, IIRC.  I do not see this used very much.
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39717499
Here's an example:
http://www.laprbass.com/RAY_temp_sim1980_form.php

<?php // RAY_temp_sim1980_form.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28317857.html
// SELECT MULTIPLE


// SHOW THE REQUEST DATA, IF ANY
echo '<pre>';
var_dump($_POST);
echo '</pre>';

// HERE ARE THE VALID CHOICES
$colors = array
( 'red'
, 'blue'
, 'green'
);

// GENERATE THE SELECT OPTIONS
$opts = NULL;
foreach ($colors as $option)
{
    $opts .= '<option value="' . $option . '">' . $option . '</option>' . PHP_EOL;
}

// GENERATE THE FORM
$form = <<<EOD
<form method="post">
<select name="color[]" multiple>
$opts
</select>
<input type="submit" />
</form>
EOD;

echo $form;

Open in new window

HTH, ~Ray
0
 
LVL 11

Expert Comment

by:N R
ID: 39717501
Here you go. Here is an example of a multiselect list box as you requested.
<form action="form_action.asp">
<select id="cars" name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

Open in new window


Example of it working here:
http://jsfiddle.net/gallitin/HxSvR/
0
 

Author Comment

by:Sim1980
ID: 39717535
Thanks.

I updated my code in Scheduling.php and it is now a multi select list box. But when I tried submitting the data, it wasn't inserting workscheduleid into the table, it was inserting a 0. How do I change my insert statement in ProcessWorkSchedule_PM.php to insert all of the selected workschedules?

 <div class="input nobottomborder">
                 <div class="inputtext">New Work:</div>
                 
                     <div class="inputcontent" ><select name="WorkSchedule[]" multiple id="WorkSchedule" style="width: 225px"><option selected="selected"></option>    
                
                <?php foreach($data1 as $row) { printf("<option value='%s'>%s</option>", html_escape($row['workscheduletypeid']), html_escape($row['workscheduledescription'])); }?>
                 	</select></div>  
   
            </div>

Open in new window

0
 
LVL 11

Accepted Solution

by:
N R earned 250 total points
ID: 39717549
You need a loop.  Here is an example.

$workschedule = $_POST['WorkSchedule'];

foreach($workschedule as $work)
        {
        $sql="insert into table(fieldname)
        values('$work')";
        $db->query($sql);
        }

Open in new window

Edited:

Note to anyone reading this in the future.  Do not use external data in a query without sanitizing it or at least escaping the data.  This article will explain what you need to do.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39717984
Thanks for the points and before you get your data base destroyed by hackers, please learn about how to escape external data for use in a query. ~Ray
0
 
LVL 11

Expert Comment

by:N R
ID: 39718004
Ok, taking a look at your article now ray, what does this command do to the post?

$mysqli->real_escape_string
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Wordpress Pagination Function Not working ? 7 39
PHP Echo with auto submit 8 28
Ahax pagination 9 32
Add a loading gif while php runs server side 15 30
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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.

856 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