0

I have a few checkboxes that i want to insert their values into a database if they are checked.

HTML:
<input type="checkbox" id="m1" name="category[]" value="1"/>
<input type="checkbox" id="m2" name="category[]" value="2"/>
<input type="checkbox" id="m3" name="category[]" value="3"/>
<input type="checkbox" id="m4" name="category[]" value="4"/>
<input type="checkbox" id="m5" name="category[]" value="5"/>

I can print out the category array fine and it gives me the correct values according to which checkboxes i clicked. I just can't seem to loop through them to insert multiple rows in my database.

After inserting into database the database should look like this:

| USERID | MACHINEID | 
----------------------
|      1 |         1 |  
|      1 |         2 |   
|      1 |         3 |  

If i only click the first 3 checkboxes.

I was thinking something like this:

$array_zone = $_POST['category'];
if(isset($_POST['category']))
{
 for($i = 0; $i < count($array_zone); $i++)
{
 mysql_query("INSERT INTO `userPlanDetail` (`user_id`, `machine_id`) VALUES ('$user_id', '  $array_zone[$i]')");
 }
} 
TheNameHobbs
  • 679
  • 7
  • 21
  • 36
  • incorrect logic. $_POST may have data, but the category section may be empty. Your sample code is also vulnerable to [SQL injection attacks](http://bobby-tables.com), so don't use this code at all. – Marc B Jun 11 '13 at 20:35
  • Thanks for the info, but right now i'm just trying to get the checkboxes inputted into the database. Securing it after that is simple – TheNameHobbs Jun 11 '13 at 20:40
  • Just want to also mention you should be escaping the values before directly placing them in the query. Look up SQL injection. – Brad Christie Jun 11 '13 at 22:55

2 Answers2

1

try this, looks you you have white space issues

mysql_query("INSERT INTO `userPlanDetail` (`user_id`, `machine_id`) VALUES ('$user_id', '$array_zone[$i]')");

also if there are multiple it would be better insering them like this

 mysql_query("INSERT INTO `userPlanDetail` (`user_id`, `machine_id`) 
VALUES ('$user_id', '$array_zone[$i]'), ('$user_id', '$array_zone[$i++]')");

they will insert much quicker as a single statement

Look here for more info

Multiple mysql INSERT statements in one query php

also even for testing, mysql_* is still very bad practice.

Community
  • 1
  • 1
exussum
  • 18,275
  • 8
  • 32
  • 65
0

If your machineid column is an int it's possible that the space in ' $array_zone[$i]' is causing you trouble. Are you checking for mysql errors?

  • Currently i'm not checking for errors. I just did and it says foreign key constraint fails. Both the user_id and machine_id are foreign keys – TheNameHobbs Jun 11 '13 at 21:18