Add values of multiple selected checkboxes with comma

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinpkl
    New Member
    • Oct 2008
    • 41

    Add values of multiple selected checkboxes with comma

    hi all

    i want to insert all selected checkboxes values with a comma separator in
    database in one single column.

    i m able to echo all the checkboxes selected through the below code

    Code:
    <input  type="checkbox" value="Battery"  name="checkbox[]" id="checkbox[]" />
    Code:
    for ($i=0; $i<count($_REQUEST['checkbox']);$i++) {
    echo "chosen<br />$i. ".$_REQUEST['checkbox'][$i];
    }
    ouput is
    Code:
    0. battery
    1. rocket
    2. pineapple
    i want to insert all selected checkboxes values with a comma separator in
    database in one single column.

    so what should i write in my query

    Code:
    $query = "insert into checkbox table (checkboxes) values()"
    vineet
  • CoryThompson
    New Member
    • Nov 2009
    • 2

    #2
    Something like this should work. (haven't tested)
    Code:
    for ($i=0; $i<count($_REQUEST['checkbox']);$i++) {
     $values .= $_REQUEST['checkbox'][$i].", ";
    }
    $query = "INSERT INTO table ('columnid', `columnvalue`) VALUES ('1', '".$values."');";

    Comment

    • vinpkl
      New Member
      • Oct 2008
      • 41

      #3
      thank CoryThompson

      that works perfect as needed.

      just a last question can i replace comma with numbers 1,2,3

      like

      1. first checkbox
      2. second checkbox

      vineet

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        Originally posted by vinpkl
        i want to insert all selected checkboxes values with a comma separator in
        database in one single column.
        This is not a good idea. The first rule of relational database design is to never put more than a single piece of data into a single field. When you do that, the database server considers all the values as a single string, and thus can not process them in any other way than as a single string. You can't search them, sort them, or even return them without needing front-end code or an overtly complex query to do so.

        The consequences of using a non-normalized database may not be immediately apparent, but it will likely come back to bite you if you ever need to add or alter the functionality of your application.

        Originally posted by CoryThompson
        Something like this should work. (haven't tested)
        Code:
        for ($i=0; $i<count($_REQUEST['checkbox']);$i++) {
         $values .= $_REQUEST['checkbox'][$i].", ";
        }
        $query = "INSERT INTO table ('columnid', `columnvalue`) VALUES ('1', '".$values."');";
        You can use the implode function there instead of the for loop:
        [code=php]$list_str = implode(",", $array);[/code]

        Comment

        Working...