Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2004
    Posts
    28

    Unanswered: extra value gets added in db when storing checkbox data

    I have a page that has multiple checkboxes, when the user submits the form the values are stored in a table food_cat_client which is an associate table to food_cat and client.


    This creates the text boxes based on the data in the database
    $sql2="SELECT food_cat_id, food_cat_name FROM food_cat";
    $result2 = mysql_query ($sql2);
    $count2=mysql_num_rows($result2);
    while($nt2=mysql_fetch_array($result2)){
    echo "$nt2[food_cat_name]:<input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"$nt2[food_cat_id]\">" ;
    }
    This is what i have to insert the checked items into the database.
    $checked_count=count($_POST[checkbox]);
    for($i=0;$i<=$checked_count;$i++){
    $food_cat_id_checked = $checkbox[$i];
    $sql5= "insert into food_cat_client (food_cat_id, client_id) values ('$food_cat_id_checked', '$client_id')";
    $result5 = mysql_query($sql5);

    everything works and is inserted correctly except the value 0 gets added into the db with the client_id. So for example checkboxes 2 and 6 were checked with a client_id of 24

    the table looks like this
    food_cat_id | client_id
    ---------------------
    2 24
    6 24
    0 24


    0 always gets added in the food_cat_id column no matter what combination you choose.
    Thanks for any help.
    -John
    Last edited by johnnysc; 02-13-07 at 13:49.

  2. #2
    Join Date
    Apr 2006
    Location
    Denver, Co. USA
    Posts
    242
    Hmm. Tried to answer this before but the DB died.

    The following line in your code -
    PHP Code:
    for($i=0;$i<=$checked_count;$i++){ 
    Loops one extra time and on the last time, there is no data and it probably inserts a default value for your column.

    For your example, you have two pieces of data -
    $checkbox[0] = 2
    $checkbox[1] = 6

    and $checked_count is 2. However that for loop loops three times -
    $i = 0
    $i = 1
    $i = 2 (because it uses a <= comparison.) So, make the for loop use a < comparison only.

  3. #3
    Join Date
    Nov 2004
    Posts
    28
    changed to < instead of <= and it still is adding that extra 0 value.

  4. #4
    Join Date
    Oct 2002
    Location
    Plymouth UK
    Posts
    116
    A much simpler approach and the one I routinely use would be:
    Code:
    foreach($_POST[checkbox] as $food_cat_id){
      $sql5= "insert into food_cat_client (food_cat_id, client_id) values ('$food_cat_id', '$client_id')";
      $result5 = mysql_query($sql5); 
    }

Posting Permissions

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