Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2009
    Thanked 0 Times in 0 Posts

    insert checkbox value in separate column fields - mysql


    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

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,745 Times in 4,707 Posts
    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.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts