Ahmad Azizov
Ahmad Azizov

Reputation: 166

Retrieving the checked state of a checkbox in PHP

I have this line of code to send the value of checkbox to the database(1 or 0).

$premiere = (bool)$_POST['premiere'] == true ? 1 : 0;

When I check the checkbox and click save, it works. However, when I do the opposite (leaving it unchecked), I get a problem: The checkbox doesn't seem to send the "unchecked" value to the database. The code treats $premiere as "true" always. Am I missing something?

Upvotes: 0

Views: 85

Answers (1)

Tom Smilack
Tom Smilack

Reputation: 2075

First, this is not JavaScript, your problem is between HTML and PHP.

An unchecked checkbox will not send a value to the server. You should use isset to check whether it is checked:

$premiere = isset($_POST['premiere']);

Also, when checking a boolean, you don't need == true.

Upvotes: 2

Related Questions