Retrieve the checkbox value with php

0

In the database I have the column Active type tinyint(1)

In the form

<input type="checkbox" id="proActive" name="proActive" checked value="1">

I send it by method POST and I receive it ...

$active = filter_input(INPUT_POST, 'proActive', FILTER_VALIDATE_BOOLEAN);

In theory the value of $active would be 0 or 1 , but only take the value of 1 when this checked but if you do not check proActive comes as not signed.

I've done it this way ...

if (!isset($_POST['proActive'])) 
$active = 0;

and it works, the question is

Is there in PHP any conditional as if (condicion, valorVerdadero, ValorFalso) so that it is more practical? Well I have 24 checkbox in the form.

Thanks for your help

    
asked by Juan Carlos 04.02.2018 в 10:21
source

2 answers

1

First I would group all the checkboxes in an array to pass them all at once per post.

Then you can use the foreach ($_POST['checkboxes'] as $value) loop to go through the 24 options and save the values in an array.

I could stay in such a way:

$active = []; 

foreach ($_POST['checkboxes'] as $opcion) {
   if ($option) {
      $active[$opcion] = 1;
   }else{
      $active[$opcion] = 0;
   }
 }

Then you just have to go through the array and update the values in the database.

    
answered by 04.02.2018 в 11:24
0

The problem arises because when the input type checkbox is not checked , this value is not sent directly, which causes the error you mention.

Since filter_input returns:

  

In case of success, value of the requested variable, FALSE if the filter fails or NULL if the variable variable_name is not defined. If the flag FILTER_NULL_ON_FAILURE is used, returns FALSE if the variable is not defined and NULL if the filter fails.

One solution, as the documentation says, is to use the flag FILTER_NULL_ON_FAILURE .

Example:

$active = filter_input(INPUT_POST, 'proActive', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

On the other hand, you should consider that if the filter fails will return NULL , so if you would like to avoid further analyzing this other case, then you could force the result to boolean by casting

Example:

$active = (bool) filter_input(INPUT_POST, 'proActive', FILTER_VALIDATE_BOOLEAN);

Finally, there is the ternary operator with the which you can do to write the check following the logic that you plan.

Example:

$active = $_POST['proActive'] == 1 ? true : false;
    
answered by 04.02.2018 в 16:05