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.
Hope that helped.