I am making a survey and I want to post data to my database. But I run into a problem, if I want to post checkbox data it will only post the last checked box. Hope I can get some help, here is the code:
html
<form name="x" id="submit1" action="confirm_medici.php" method ="post" onsubmit="validator();return false;" target="_self">
<input type="checkbox" name="opsystem" value="Android">Android<br>
<input type="checkbox" name="opsystem" value="Windowsphone">Windows Phone<br>
<input type="checkbox" name="opsystem" value="Ios">IOS (Apple)<br><br>
Else: <input type="text" name="opsystem" size="75"><br>
php
<?php
$con=mysqli_connect("x","x","x","x");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$question1=$_POST['opsystem'];
$sql="INSERT INTO medici (colum1)
VALUES
('$question1')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Rename the field so the name ends with the characters []
. PHP will then expose it as an array instead of dumping all but the last item.
name="opsystem[]"
$_POST['opsystem']
If your checkbox is multiple choice, you can just add []
to the end of the checkbox name.
<input type="checkbox" name="opsystem[]" value="...">...</input>
And then in php:
$checkbox = $_POST['opsystem'];
foreach ($checkbox as $item) {
... Database Insertion Code For Each Checkbox Here
}
In the foreach you can then run a query to insert the answer into the database. Or you could implode the array instead of running a foreach over it, and insert the new string into the database.
With Implode:
$checkbox = $_POST['opsystem'];
$checkboxResults = implode(',', $checkbox);
$sql = 'INSERT INTO medici (column1) VALUES ('.$checkboxResults.')';
I will also point out that this SQL is NOT GOOD! It is open to sql injections.