Reputation: 39
I am trying to get values from a form into my database as boolean type.
Basically, each question has many checkboxes, and if a user checks the box, i want it to put in 1 for true and whichever ones are not checked to insert 0.
I have attempted to get them in, however no luck.
Please see additional code/snippets below.
Can someone please help?
<h1>Question 1</h1><br>
</br>
<input type="checkbox" name="1" value="1">Item1
<input type="checkbox" name="2" value="2">Item2
<input type="submit" name="submit" value="save" class="button-form">
PHP CODE:
if(isset($_POST['submit'])){
try{
$Query = $db->prepare('INSERT INTO Results ( 1, 2 ) VALUES (:1, :2)');
$Query->execute();
Upvotes: 1
Views: 2164
Reputation: 345
If a checkbox isn't checked (see "checked"-Attribute of input type checkbox), nothing is sent to the server.
$_POST['B1']
gets the value of the element with NAME 'B1' if it is sent to the server.
So
$b1 = (isset($_POST['B1'])) ? 1 : 0;
should do the trick. $b1 will be 0 if the checkbox is unchecked and 1 if it is checked.
Option 1 The SQL looks like you are trying to put something like 01100 into the database field 'B2'. Usually you would store the result of every checkbox in a single database column. But if you really want to concat them, your code should look like this:
$stmt = $conn->prepare('INSERT INTO Results ($UserID, B1, B2 ) VALUES (:UserID, :B1, :B2, :B3, :B4, :B5, :B6);');
$stmt->execute(array(
':UserID' =>$_POST['UserID'],
':B1' =>$_POST['B1'],
':B2' =>(isset($_POST['B2'])) ? 1 : 0 + (isset($_POST['B3'])) ? 1 : 0 + (isset($_POST['B4'])) ? 1 : 0 + (isset($_POST['B5'])) ? 1 : 0 + (isset($_POST['B6'])) ? 1 : 0
));
Option 2 If you have one database field for every B1...B6-value then you've forgotten to take these columns into your SQL-INSERT-Statement:
INSERT INTO Results ($UserID, B1, B2, B3, B4, B5, B6) [...]
And your stmt execute is wrong and should be:
$stmt->execute(array(
':UserID' =>$_POST['UserID'],
':B1' => isset($_POST['B1']) ? 1 : 0,
':B2' => isset($_POST['B2']) ? 1 : 0,
':B3' => isset($_POST['B3']) ? 1 : 0,
':B4' => isset($_POST['B4']) ? 1 : 0,
':B5' => isset($_POST['B5']) ? 1 : 0,
':B6' => isset($_POST['B6']) ? 1 : 0
));
Upvotes: 0
Reputation: 14071
When a checkbox isn't checked, it's not sent. That means it is not set to zero if unchecked.
What does that mean? It means you need to check if it's sent or not. If yes, it's 1, if not - it's 0.
The code you're after is the following:
$stmt->execute(array(
':UserID' =>$_POST['UserID'],
':B1' => isset($_POST['B1']) ? 1 : 0,
':B2' => isset($_POST['B2']) ? 1 : 0,
':B2' => isset($_POST['B3']) ? 1 : 0,
':B2' => isset($_POST['B4']) ? 1 : 0,
':B2' => isset($_POST['B5']) ? 1 : 0,
':B2' => isset($_POST['B6']) ? 1 : 0
));
Upvotes: 2