View Full Version : insert checkbox value in separate column fields - mysql

03-27-2009, 06:45 PM

Thank you for any suggestions. Trying to know whether a checkbox is selected or not. would like a 0/1 value in each column in db as relates to each checkbox?

Example of how we'd like it to work

week1 - not selected
week2 - selected
week3 - selected
week4 - not selected


id --- w1 --- w2 --- w3 --- w4
1 ----- 0 ---- 1 ----- 1 ----- 0

however here is my code and it does create one row in the database and the correct implode values do appears based on what was selected (week2, week3) - however I don't know how to run through each of checkboxes and put a 0 in the ones that weren't selected and 1 in those that were selected instead of their value.

what's happening in my db

id --- w1 ---- w2 ----- w3 ---- w4
1 ---- (w2) -- (w3)

then obviously get the error that the column amt doesn't match. - I have the values inserting... however would like just a 0 for not selected and 1 for selected!

$summer_weeks = $_POST['summer_camp'];

$query = 'INSERT INTO userweeks (week_id, w1, w2, w3, w4, w5, w6) VALUES (NULL, ';

$add = "'".implode("','",$summer_weeks)."'";
for($i = 0; $i > $count; $i++) {
$add .= ",NULL";
$query .= $add.')';
$result = @mysql_query ($query);

Thank you for any suggestions

Old Pedant
03-28-2009, 07:03 AM
An UNCHECKED checkbox sends *NOTHING AT ALL* from the HTML page to the server.

I am *NOT* a PHP programmer, *AT ALL*, so I don't know the easy way to do this in PHP, but I believe you could do something like this:

I assume that in the <FORM> you have

<input type=checkbox name="week1">
<input type=checkbox name="week2">
<input type=checkbox name="week6">

Note that the value= of the checkbox is of NO IMPORTANCE at all.

So then the PHP code:

$query = 'INSERT INTO userweeks (week_id,w1, w2, w3, w4, w5, w6) VALUES (NULL';
for($i = 1; $i <= 6; $i++)
$query .= isset($_POST['week' . i] ) ? ',1' : ',0';

Note that you should *NOT* try to get all the values of all the checkboxes in a single $_POST call, because HTML won't cooperate with you!

You *COULD* do it by using JavaScript to help: Upon submit, you have the JS code run through all the checkboxes. Any unchecked checkbox, it BOTH changes the value (e.g., from 1 to 0) and then checks it. But now you are dependent on JS in the browser for no really good reason. If you do it as above, it always works.