POSTing Checkboxes with Submit button to MySQL database - php

Currently, I have a piece of code which displays four checkboxes and allows a user to select the checkboxes, click submit, and the data, through the POST method, will be sent to the database (called "Spreadsheet") where it would be stored.
Typically, with a radio button, the data stored is only one element. But I noticed that with checkboxes, the elements (for my case specifically) could range from zero to four items. So my issue with my code is, only one element gets stored, even if I press all four. I think I have to store the items as an array, but how do I store + retrieve said items to and from the database?
Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <!-- tells browser this is an HTML document -->
<head> <!-- container of all head elements --> </head>
<body> <!-- Begin the content of the document -->
<?
if (isset($_POST['formSubmit2'])){
$category = $_POST['category'];
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
while($row = mysql_fetch_array($query)){
$values = array('0 - Luxury','1 - Brand','2 - Retailer','3 - B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category" value="<?php echo $values[$i]; ?>" id="rbl_0" <? if($row['category'] == $i) echo "checked='checked'"; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
</body>
</html>

Instead of passing in name="category", set it to "$category[]".
You should be able to retrieve it from $_POST, set it to a new variable, and manipulate it how you want.
if (isset($_POST['formSubmit2'])){
$submitted_category = $_POST['$category'];
$accountID = $_POST['accountID'];
// rest of your code...
}
Hope that helped.

You have to give each checkbox a different name because you are overwriting their values if not.
You can also give them an array name like category[] resulting in something like this:
<input type="checkbox" name="category[]" value="value 1"/> value 1<br/>
<input type="checkbox" name="category[]" value="value 2"/> value 2<br/>
<input type="checkbox" name="category[]" value="value 3"/> value 3<br/>
And then retrieve them with:
$categories = $_GET['category'];
foreach($categories as $category){
echo "Selected " . $category . "<br/>";
}
See as well: How do I create arrays in a HTML ?Docs

You can serialize your array and then store it in a varchar column in your DB
Save:
$values = array(...);
$data = serialize($values);
// Store data in your database
Retrieve:
// $data should come from your DB
$values = unserialize($data);
// Now values holds your array

For sending multiple values in HTTP POST request upon form submission you need to define HTML array.
Please refer the below code snippet
<input type="checkbox" name="category[]" value="0"/>Luxury
<input type="checkbox" name="category[]" value="1"/> Brand
<input type="checkbox" name="category[]" value="2"/> Retailer
<input type="checkbox" name="category[]" value="3"/> B2B
POST values for checkbox will be accessible through superglobal variable $_POST['category']
Here S_POST['category'] will be accessible as an array.
e.g $_POST['category'][0],
$_POST['category'][1],
$_POST['category'][2],
$_POST['category'][3]
So you need to iterate through an array for insertion of individual values for checkbox.

Related

Store the array elments based on checkbox checked?

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal. I am displaying my check boxes in a for loop.
Here I am getting the all values in an array, but I want store the array elements based on the check box checked.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
//echo $arr[$j];
$j++;
} ?>
My checkbox code:
<form id="check_all" action="" method="POST" name="check" >
<input type="checkbox" class="multid[]" id="<?php echo $products->getId();?>" value="checked" /> </form>
What do I have to do in order to get checked values in my array? Did I do anything wrong?
Use input name attribute
<input type="checkbox" name="multid[<?php echo $products->getId();?>]" value="checked" />
No in you php code, check if multid[yourProductId] is set, and store them if it is set.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
if(!empty($_GET['multid['.$arr[$j].']']))
its checked, do something.
//echo $arr[$j];
$j++;
} ?>
After submiting the form you can get an array of checked products with $_POST['multid']
Can you use javascript? Try this one.
HTML:
<input type="hidden" id="hdnCheckedIDs" value="" />
Before submit, on submit button's client click, Javascript:
var CheckedIDs = "";
for each checkbox
if(document.getelementbyid('multid1').checked)
CheckedIDs = CheckedIDs + document.getelementbyid('multid1').id;
document.getelementbyid('checkboxID') = CheckedIDs;
In PHP, you can use this comma seperated string $_POST['hdnCheckedIDs'] to get the IDs of checked chekboxes.

Retrieve POST checkbox data from form if they exist

Hello knowledgeable people. I am having trouble retrieving checkbox data from form. I have a site in which user can add checkboxes themselves, so I am writing them out like this:
<table style="padding:10px;">
<?php
$query_boolean = $DB->prepare("SELECT * FROM moduls WHERE type='boolean'") or die(mysql_error());
$query_boolean->execute();
while (($row = $query_boolean->fetch()) != false)
{
?>
<tr>
<td>
<?php echo $row->name ?>:
</td>
<td>
<?php
$s = "";
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="yes">%s', $row->id, Yes);
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="no">%s', $row->id, No);
echo $s;
?>
</td>
</tr>
<?php
}
?>
</table>
Now I have an advanced search in which I have to chech through every checkbox to see what has been selected (ether none, Yes, No, or both). How can I get the info from every checkbox in variables? Thank you so much!
To get POST data from checkboxes they must have attribute
checked="checked"
EDIT:
If you have 2 checkbox as this..
<input type="checkbox" checked="checked" class="textbox" name="boolean_yes" value="yes">
<input type="checkbox" class="textbox" name="boolean_no" value="no">
When you submit your form the checkbox with attribute checked will be sent as POST and the one without checked attribute will not be sent..
if(isset($_POST['search'])) {
$all_checked = array();
foreach($_POST as $key=>$value){
if(strpos($key, "boolean_") > -1){
$all_checked[$key] = $value;
}
}
var_dump($all_checked);
}
This way you will get inside $all_checked array all marked boxes.. All others checboxes are not marked!
if you want to get checkbox value then use checkbox name as array
<input type="checkbox" name="email1[]" value="">
an get it on another page by
<?php
$var2 = $_POST['email1'];
$v=implode(",",$var2);
echo $v;
?>
try it

Validate checkboxes sent in array

I have a form with multiple checkboxes, which I want to put into an array. I go by the example provided here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
So I've prepared the files:
checkboxes.php:
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags[]" value="1" />1<br>
<input type="checkbox" name="tags[]" value="2" />2<br>
<input type="checkbox" name="tags[]" value="3" />3<br>
<input type="checkbox" name="tags[]" value="4" />4<br>
<input type="submit" value="Send" />
</form>
checkboxes2.php:
<?php
print_r($_POST["tags"]);
?>
Pretty simple...I realize I should only get the value of these textboxes and not if they have been selected or not. But I still get this error:
Undefined index: tags in checkboxes2.php on line 2
I have absolutely no idea what I did wrong here. I went by the example in the link above and did everything exactly the same (mainly copy/pasting and changing some parts like adding a submit button) but I don't get the output as shown in the example. I should at least get the values of each of these checkboxes, right?
What I want to do: I want to check the array of checkboxes, see which ones have been selected and add "yes" or "no" into a second array, like this:
<?php
$number1 = $_POST["tags"];
$number2 = array();
foreach($number1 as $number1_output)
{
if(isset($number1_output))
{
$number2[] = "yes";
}
else
{
$number2[] = "no";
}
}
print_r($number2);
?>
Well...it only half works. Only the checkboxes that have been selected are added to the array. So if I select "3" and "4" I get this:
Array ( [0] => yes [1] => yes )
What is the best way to deal with checkboxes in arrays and validating them?
Checkboxes which are not selected to do not send anything when the form submits. That means if NONE of those tags checkboxes are selected, there will be no tags attribute in the $_POST array.
As such, your code should be
<?
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['tags'])) {
print_r($_POST['tags']);
}
}
?>
The first line verifies that a POST has actually taken place, and the second line verifies that there's actually any data to dump out.
For the rest of your code, the isset is rather pointless... Since a checkbox is only present in the POST data if it was selected, there's no point in doing the isset() within your foreach loop - there'd be nothing to foreach on if there were no checkboxes, so by definition everything in the foreach will be isset() == true anyways.
As such, your foreach loop will only produce yes values, never a no.
A better workaround is to specify array keys within your form:
<input type="checkbox" name="tags[1]" value="1" />
<input type="checkbox" name="tags[2]" value="2" />
etc...
then have
<?php
if (b blah blah blah verify post stuff) {
for ($i = 1; $i <= $max_tags_allowed; $i++) {
if (isset($_POST['tags'][$i])) {
$message2[] = 'yes';
} else {
$message2[] = 'no';
}
}
}
Alternatively, if you want to have checkboxes that also send a value if they are not checked, you can add a Hidden input field before the checkbox:
<input type="hidden" name="tag[1]" value="off" />
<input type="checkbox" name="tag[1]" value="on />
Because the checkbox is only sent if it is set, but it overrides the hidden as it is later in the HTML, you will now always have tag[1] set with either 'off' or 'on' depending on whether or not the box was checked.
First create an array that holds "no" with all the possible keys, like this:
$no = array(0 => "no", 1 => "no"); // or array("no", "no");
Then you can get your desired array like that:
$checkValues = array_flip($_POST["tags"]) + $no;
This way the values in $_POST["tags"] will become keys, and the + operator merges the two array keeping the keys, also omitting values from the second array, if they are present in the first array. This way you can just check like this:
$fourthChecked = $checkValues[4] !== "no";
I thought its much simpler than the other answers. Good luck!
In your checkboxes.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>My form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" languaje="javascript">
$(document).ready(function() {
$('.checkbox').click(function(){
var values="";
$('.checkbox:checked').each(function(index) {
values+=$(this).val();
$('#tagsVal').val(values);
});
});
});
</script>
</head>
<body>
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags1" value="1" class="checkbox"/>1<br><!--Notice the class="checkbox" attribute is important for the jquery function-->
<input type="checkbox" name="tags2" value="2" class="checkbox"/>2<br>
<input type="checkbox" name="tags3" value="3" class="checkbox"/>3<br>
<input type="checkbox" name="tags4" value="4" class="checkbox"/>4<br>
<input type="hidden" name="tagsVal" id="tagsVal" value="" />
<input type="submit" value="Send" />
</form>
</body>
</html>
So what you'll get in your $_POST['tagVal'] you'll get your values. If checkbox 1,3 and 4 are checked you'll get a string 134.
In your checkboxes2.php you'll only have to split the string into array if you need it.
$arr1 = str_split($_POST['tagVal']);
Regards
Luis

Populating checkboxlists from database

Is it possible to populate a checkboxlist from the database values? If so, please suggest how to do this.
$query2 = "select * from Products where CategoryID = '$CategoryName' ";
mysql_query($query2) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($query2)){
$array[] = $row;}
foreach($array as $val)
{
if($val =='the checkbox value')
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
These are the few steps you have to do.
1.Fetch the values from database.
2. Covert the values in array as they are stored as string by (,) separated.
3. Then
foreach($values as $val)
{
if($val =='Bike')
{
$bikeflag = '1';
}
if($val =='Car')
{
$carflag = '1';
}
}
<form>
<input type="checkbox" name="vehicle" value="Bike" <?php if(isset($bikeflag ) =='1'){ ?>checked = checked <?php } ?>/> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" <?php if(isset($carflag) =='1'){ ?>checked = checked <?php } ?>/> I have a car
</form>
Hopefully this will help you.
Get values from database with the appropriate SQL query
Loop through results echoing out a checkbox element
Caveats
Make sure each one has a unique name unless you want them to be an array. Then use array syntax for their name (e.g. name[])
Make sure to give each one a unique value
Yes, its very much possible:
Fetch the records to be populated with the structure:
Id and value
Provide datasource of the checkedbox list as the fetched structured list as mentioned above.
Now define the value field of the checkboxlist as "Id" and text as "value"

Updating Already Checked Checkboxes in PHP

let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.

Categories