Michael
Michael

Reputation: 9

How do I insert multiple checkbox values into database?

How do I insert multiple checkbox values into database? Here is my code, it workes for the radio buttons where there is only one value, but how do I insert more if I have checkboxes?

PHP CODE:

if(isset($_POST['radio']) &&
    isset($_POST['checkbox'])){

    $radio = $_POST['radio'];
    $checkbox= $_POST['checkbox'];

    $sql = "INSERT INTO info(radio, checkbox)VALUES ('$radio', '$checkbox')";
    $result = mysql_query($sql);

}

HTML CODE:

<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>

<input type="checkbox" name="checkbox" value="1">1<br>
<input type="checkbox" name="checkbox" value="2">2<br>
<input type="checkbox" name="checkbox" value="3">3<br>
<input type="checkbox" name="checkbox" value="4">4<br>
<input type="checkbox" name="checkbox" value="5">5<br>
<input type="checkbox" name="checkbox" value="6">6<br>

Upvotes: 0

Views: 3152

Answers (3)

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Html

<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>

<input type="checkbox" name="checkbox[]" value="1">1<br>
<input type="checkbox" name="checkbox[]" value="2">2<br>
<input type="checkbox" name="checkbox[]" value="3">3<br>
<input type="checkbox" name="checkbox[]" value="4">4<br>
<input type="checkbox" name="checkbox[]" value="5">5<br>
<input type="checkbox" name="checkbox[]" value="6">6<br>

Php

use a foreach to get all the values of checkboxes

//Do the necessary coding and then
if(!empty($_POST['checkbox']))
   foreach($_POST['checkbox'] as $key=>$value){
      if(trim($value) != ''){
         //Do insertion here
      }
   }
}

Upvotes: 2

FrimInc
FrimInc

Reputation: 31

use php core functions serialize() and unserialize()

Upvotes: 0

rray
rray

Reputation: 2556

change the names of yours checkboxes to:

<input type="checkbox" name="checkbox[]" value="1">1<br>
<input type="checkbox" name="checkbox[]" value="2">2<br>
<input type="checkbox" name="checkbox[]" value="3">3<br>
<input type="checkbox" name="checkbox[]" value="4">4<br>
<input type="checkbox" name="checkbox[]" value="5">5<br>
<input type="checkbox" name="checkbox[]" value="6">6<br>

on php do it:

$radio = $_POST['radio'];
$sql = 'INSERT INTO info(radio, checkbox)';

foreach($_POST['checkbox'] as $item){
    $sql .=  "VALUES('$radio', '$item')," ;
}

$sql = trim($sql, ','); //remove the last ',';
//performe all insert at once.

avoid to use mysql_* functions, try PDO

Upvotes: 0

Related Questions