-1

I have this checkbox in my form:

<input type="checkbox" name="private" id="private" />

When I submit my form, the checkbox always returns on, even when I didn't check it.

echo $_POST['private'] //result is always returns on

$private = isset($_POST['private']) ? 1 : 0; //result is 1 always

What am I doing wrong?

user2342558
  • 5,567
  • 5
  • 33
  • 54
user979331
  • 11,039
  • 73
  • 223
  • 418

3 Answers3

1

Give the input a value and check that:

<input type="checkbox" name="private" id="private" value="1"/>

$private = isset($_POST['private']) && $_POST['private'] == 1 ? 1 : 0;
Danny Thompson
  • 1,526
  • 1
  • 11
  • 18
0

isset($_POST['private']) will always return true, because $_POST['private'] is exists.

Add value to checkbox <input type="checkbox" name="private" id="private" value="1" /> and use $private = $_POST['private'] ? 1 : 0; or if you are use PHP 7+ $private = $_POST['private'] ?? 0;

Levente Otta
  • 713
  • 6
  • 17
0

When you submit an HTML form, the $_POST['input_name'] for checkbox elements are always set, so your isset($_POST['private']) always returns true.

You should instead be directly checking the value of the checkbox elemenet like so:

$private = $_POST['private'];

This will give you your desired result, if the checkbox is checked, $private will equal 1, otherwise 0.

coderodour
  • 1,072
  • 8
  • 16