0

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);
?>

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

2 Comments

That's the first step, but then there's the INSERT with values of Array.
@ChrisForrence — Use a for loop over the array and insert each time you go around the loop.
1

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.

2 Comments

I tried it, but every time I try to use the explode or forecast function I get error messages like this: Warning: implode() [function.implode]: Invalid arguments passed in
If it is giving that error with implode, it sounds like your $_POST does not contain 'opsystem'. Try a var_dump($_POST)` and make sure that $_POST contains the data you have sent using the form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.