By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,650 Members | 753 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,650 IT Pros & Developers. It's quick & easy.

INSERT values into mysql table with PHP using checkboxes

P: 2
Hello everyone,

I'm working on adding checkboxes to the edit_profile section where members should be able choose with checkboxes the multiple options of massage techniques offered... When I checked only one, either, option 1, or option 2 or option 3 I'm able to see it in the column in the correct table of mysql but when I check more then one box only the last box would insert into the column, ignoring the rest. In this case, if I check the three options, only lomi lomi would insert into the column... I hope you guys can help me. Here is the code:

Expand|Select|Wrap|Line Numbers
  1. // set all checkboxes to false initially
  2.  
  3. $Deeptissue="";
  4.  
  5. $Swedish="";
  6.  
  7. $Lomilomi="";
  8.  
  9. $checkbox=$_POST['typeTech'];
  10.  
  11. //if appear in the POST, they are checked, set to true
  12.  
  13. foreach($checkbox as $typeTech ) {
  14.  
  15. if($typeTech=="deeptissue")
  16.  
  17. $Deeptissue="Deep Tissue";
  18.  
  19. else if($typeTech=="swedish")
  20.  
  21. $Swedish="Swedish";
  22.  
  23. else if($typeTech=="lomilomi")
  24.  
  25. $Lomilomi="Lomi Lomi";
  26.  
  27. }
  28.  
  29. echo "Technique checked: ".$Deeptissue."<br/>\n";
  30.  
  31. echo "Tchnique checked: ".$Swedish."<br/>\n";
  32.  
  33. echo "Technique checked: ".$Lomilomi."<br/>\n";
  34.  
  35.  
  36. $sql = mysql_query("INSERT INTO Members (Technique)
  37.  
  38. VALUES('$typeTech')")
  39.  
  40. or die (mysql_error());
Nov 1 '11 #1
Share this Question
Share on Google+
1 Reply


Dormilich
Expert Mod 5K+
P: 8,639
there are 2 problems:
- with that SQL you can insert only one value (don’t know how inserting multiple values is intended to be)
- you use a variable from the foreach construct, naturally, after the loop is done, this will only have the last value.

how to solve the second problem depends on how you tackle the first one. generally, for the insert you could do with a few lines of verification and one line for the SQL.

Expand|Select|Wrap|Line Numbers
  1. // assuming there are only the checkboxes, omitting any verification/sanitisation
  2. $res = mysql_query("INSERT INTO Members (Technique) VALUES (" . implode("), (", $_POST) . ")";
Nov 1 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.