irwan

Multi Select Box to MySql DB Table

Nov 15th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. Generate multi select box from data in db, then when submitted, each selection is written to a db table as it's own record, each tied together by a common record id.
  2.  
  3. <?
  4. //Create multi select box, pulling data from db
  5.                 $sql = "SELECT id,name FROM table ORDER BY name ASC";
  6.                 $result = mysql_query($sql);
  7.                
  8.                 if($result && mysql_num_rows($result)>0)
  9.                 {
  10.                 ?>
  11.                 <select name="id[]" size=5 multiple><option value=0 selected>Select Name...</option>
  12.                 <?
  13.                 for($i=0;$i<mysql_num_rows($result);$i++)
  14.                 {
  15.                 $arr=mysql_fetch_array($result);
  16.                 echo "<option value=" . $arr['id'] . ">".$arr['name'];
  17.                 }
  18.                 echo "</select>";
  19.                 }else
  20.                 echo "No Names in DB";
  21. ?>
  22.  
  23. <?
  24. //when multi select is submitted from form, this part processes it
  25.  
  26. $id = $_POST['id'];
  27.  
  28. foreach ($_POST['id'] as $id)
  29.        
  30.         $result_system = mysql_query("INSERT INTO diff_table (diff_id,id) VALUES ('$diff_id','" . $id . "')")or die("Insert Error: ".mysql_error());
  31.  
  32. ?>
Advertisement
Add Comment
Please, Sign In to add comment