Friday, April 19, 2013

PHP and MySQL , process post array



Suppose in the following form, we have arrays   outcome and modules to post to search_results.php
<form name="search_form" action="search_results.php" onsubmit="select_multiples(this);" method="POST">
<h5>Were outcomes measured? including the following</h5> 

<input type="checkbox" name="outcome[]" value="0" id="outcome-unknown" /> 
 <input type="checkbox" name="outcome[]" value="1" id="outcome-yes" />
 <input type="checkbox" name="outcome[]" value="2" id="outcome-no" />
<br />
<h5>Including the selected modules</h5>

 <select name="modules[]" id="modules" multiple="multiple" size="10"> </select>
</form>
In search_result.php, we use implode to combine query in MySQL query:
  $include_by_type=array();
 if(isset($_POST['outcome'])){

$sql ='SELECT event_id FROM cesei_activity_new WHERE outcome IN('.implode(',',$_POST['outcome']).')';
     $result = mysql_query($sql, $db);
      $in_events     = array();
      while($row = mysql_fetch_assoc($result)){
         $in_events[$row['event_id']] = $row['event_id'];
      }
      $include_by_type[] = $in_events;
}

if(isset($_POST['modules'])){

$sql ='SELECT event_id FROM cesei_activity_mod WHERE module_id IN('.implode(',',$_POST['modules']).')';
     $result = mysql_query($sql, $db);
      $in_events     = array();
      while($row = mysql_fetch_assoc($result)){
         $in_events[$row['event_id']] = $row['event_id'];
      }
      $include_by_type[] = $in_events;
}


  In some cases, we may need to force all the values in select box selected, for example the case for transfer selection items between box. Define   JavaScript function select_multiples for onsubmit in the form
//SELECT ALL THE OPTIONS BEFORE SUBMIT ON "TRANSFERABLE" SELECTS
function select_multiples(form){
   for(var e = 0; e<form.elements.length; e++){
      var elm = form.elements[e];
      if(elm.type.indexOf('select') >= 0 && elm.name.indexOf('[]') >= 0 && elm.className.indexOf('submit-all') >= 0){
         for(var op=0; op<elm.options.length; op++ ){
            elm.options[op].selected = true;
         }
      }
   }
}

No comments:

Post a Comment