php - Insert checkbox data into database, based on if it is checked or not

998

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 } ?> />
866

Answer

Solution:

You would change your html to:

{-code-1}

Then change the PHP to:

$is_checked = (isset($_GET['saleItem']) ? 'y' : 'n');

and then your SQL statement should look like:

$sql=("INSERT INTO table (sale) VALUES ('" . $is_checked . "')"); 

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 to1 and then checking server-side if it exists at all, is the best way to determine the state of the checkbox.

986

Answer

Solution:

A checkbox can have only one value. Your attempt to change thevalue attribute depending on whether it is checked or not won't work.

Here's updated HTML for your checkbox:

<input type="checkbox" name="saleItem" value="Y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />

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:

$saleItemValue = "N";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'Y' ){
    $saleItemValue = "Y";
}

$sql = "INSERT INTO table (sale) VALUES ( '$saleItemValue' )";
if( !mysql_query($sql) ){
    die( "could not query: " . mysql_error() );
}

This way, PHP will place an 'N' in the database if nothing comes back -- i.e. if the checkbox was not checked.

People are also looking for solutions to the problem: php - Warning: DOMDocument::loadHTML() [domdocument.loadhtml]

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.