1

I am trying to insert the value of multiple checkboxes if they are checked into one column in my database.

Here is what I have...

if(!empty($_POST['dyuhdb'])) {
    foreach($_POST['dyuhdb'] as $dyuhdb) {
        $dyuhdb . ",";
    }
}

$sql = "INSERT INTO MRF (Q1) VALUES ('". $dyuhdb ."')";

<div class="checkbox">
    <label><input type="checkbox" name="dyuhdb[]" value="1">1</label>
</div>

<div class="checkbox">
    <label><input type="checkbox" name="dyuhdb[]" value="2">2</label>
</div>

<div class="checkbox">
    <label><input type="checkbox" name="dyuhdb[]" value="3">3</label>
</div>

For some reason, if 1 and 2 are ticked, only 2 will enter into my Database?

What am I doing wrong?

2 Answers2

1

The problem is because of the following line,

$dyuhdb . ",";

In each iteration of foreach loop you're overwriting the variable $dyuhdb. Instead simply use implode() function to join the array element with a string(,) and use it in your INSERT query, like this:

if(isset($_POST['dyuhdb']) && count($_POST['dyuhdb'])){
    $checkbox_values = implode(",", $_POST['dyuhdb']);
    $sql = "INSERT INTO MRF (Q1) VALUES ('". $checkbox_values ."')";

    // execute your query
}

Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • @D.Ashbridge Just one more thing, there's no need to quote your checkbox values, `implode(",", $_POST['dyuhdb'])` will do just fine. I've updated my answer. – Rajdeep Paul May 18 '16 at 14:26
0

There will be an extra , in your Query. You could avoid the same by using built in implode function instead of looping post data.

if(!empty($_POST['dyuhdb'])) {
   /* foreach($_POST['dyuhdb'] as $dyuhdb) {
        $dyuhdb . ",";
    }*/

    $dyuhdb = implode(",",$_POST['dyuhdb']);
}
Jenson M John
  • 5,499
  • 5
  • 30
  • 46