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

x
?
Solved

How to create a multiple select drop down in php

Posted on 2013-12-13
9
Medium Priority
?
1,142 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
[X]
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
  • 4
  • 3
  • 2
9 Comments
 
LVL 12

Expert Comment

by:Nathan Riley
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 111

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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 12

Expert Comment

by:Nathan Riley
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 12

Accepted Solution

by:
Nathan Riley earned 1000 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 111

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 12

Expert Comment

by:Nathan Riley
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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

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…
This article discusses how to create an extensible mechanism for linked drop downs.
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 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 …

721 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