• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1175
  • Last Modified:

How to create a multiple select drop down in php

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
Sim1980
Asked:
Sim1980
  • 4
  • 3
  • 2
2 Solutions
 
Nathan RileyFounderCommented:
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
 
Sim1980Author Commented:
If that's the only way to be able to select multiple entries, how about a list box?
0
 
Ray PaseurCommented:
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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
Ray PaseurCommented:
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
 
Nathan RileyFounderCommented:
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
 
Sim1980Author Commented:
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
 
Nathan RileyFounderCommented:
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
 
Ray PaseurCommented:
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
 
Nathan RileyFounderCommented:
Ok, taking a look at your article now ray, what does this command do to the post?

$mysqli->real_escape_string
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now