Solved

How to create a multiple select drop down in php

Posted on 2013-12-13
9
1,082 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 108

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
 
LVL 108

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
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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 108

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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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 …

707 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

15 Experts available now in Live!

Get 1:1 Help Now