Forum Moderators: coopster
I'm thinking about creating an extra column in my Products table. That extra column would just keep a total of the number of votes each product gets - like a survey or poll. I'm not sure what to do to insert a number or value for the checkbox and then insert that into the new column to keep score. I'm new to this stuff so I hope I'm making sense. If anyone could point me in the right direction that would me great. Thanks!
while ($row=mysql_fetch_assoc($result)) {
echo '<input name="checkboxName" type="checkbox" value="1" />';
echo $row["product"];echo "<br>";
Unfortunately, unchecked checkboxes don't get posted back among the posted values. So you need to relate each checkbox to its product.
You could do this a couple of different ways. You could name each checkbox a unique name that relates it to the product - for example, if you have products: apple, banana, cherry, date
then you could name the checkboxes: checkapple, checkbanana, checkcherry, checkdate
When you process the post, you can run a query to get the product names and combine each with 'check', then see if that box was posted:
while ($row=mysql_fetch_assoc($result)) {
$checkname = 'check' . $row['product'];
if(isset($_POST[$checkname])) {
mysql_query("UPDATE Products SET votes=votes+1 WHERE product='{$row['product']}'");
} // EndIf This product got a vote
} // EndWhile run through product line
Or you could name your checkboxes:
name="checkboxName[]"
then php will return the checked ones as an array when the form is posted. In order to keep track of which product the checkbox belongs to, you could twiddle with the values:
echo '<input name="checkboxName[]" type="checkbox" value="' . $row['product'] . '" />';
Now when the form is posted, get the product names into an array:
$products = array();
while ($row=mysql_fetch_assoc($result))
$products[] = $row["product"];
Then to see if the associated checkbox is checked:
foreach($_POST['checkboxName'] as $ckbox) {
if(in_array($ckbox,$products)) {
mysql_query("UPDATE Products SET votes=votes+1 WHERE product='$ckbox'");
} // EndIf This product got a vote
} // EndForEach posted checkbox