php - Insert checkbox data into database, based on if it is checked or not
HTML:
<form action="add.php" id="form">
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="n" <?php if(isset($_GET['saleItem'])) { ?> checked="checked" value="y" <?php } ?> />
</td>
</tr>
</form>
PHP (add.php)
$sql=("INSERT INTO table (sale) VALUES ('" . $_GET['saleItem'] . "')");
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
It always inserts an N regardless if it is checked. I would love if it inserted y based on if the checkbox is checked. I also tried to put the value="n" into an else after the if, but it always put N regardless as well (i removed the value="n" previous to the if when I did this), here is what I meant:
<input type="checkbox" name="saleItem" <?php if(isset($_GET['saleItem'])) { ?> checked="checked" value="y" <?php } else { ?> value="n" <?php } ?> />
Answer
Solution:
You would change your html to:
Then change the PHP to:
and then your SQL statement should look like:
If a checkbox is not checked when the form is submitted, the browser doesn't send it's value to the server. So changing it's value to
1
and then checking server-side if it exists at all, is the best way to determine the state of the checkbox.Answer
Solution:
A checkbox can have only one value. Your attempt to change the
value
attribute depending on whether it is checked or not won't work.Here's updated HTML for your checkbox:
This will return a "Y" to the server if it is checked, but it will not return at all if it is not checked (this is the way the checkbox element is designed to work). So you need to have your PHP code explicitly check to see if anything was returned:
This way, PHP will place an 'N' in the database if nothing comes back -- i.e. if the checkbox was not checked.