D. Ashbridge D. Ashbridge - 6 months ago 12
PHP Question

Inserting MULTIPLE Checkboxes into a Database column

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?

Answer

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.