PHP form and undefined index checkbox

I get an "Undefined index" error when submitting a form with an invalid flag. Is there any other way besides running an "isset" or an "empty" check for each individual published value?

I looked through this Question and am having trouble believing that this is the only solution.

The following is an example code: EDIT: please, not that these are not actual table column names; they are called unique (e.g. postAddress, displayPhone, student, etc.),   

+3
source share
3 answers

You can write a function that checks if the checkbox has been checked:

function checkbox_value($name) {
    return (isset($_POST[$name]) ? 1 : 0);
}

:

$sql =  'UPDATE table SET '.
        'checkbox1 = '. checkbox_value('checkbox1') .','.
        'checkbox2 = '. checkbox_value('checkbox2') .','.
        'checkbox3 = '. checkbox_value('checkbox3') .','.
        'checkbox4 = '. checkbox_value('checkbox4') .','.
        'checkbox5 = '. checkbox_value('checkbox5') .','. "LIMIT 1";
+7

/ , , .

<input type="hidden" name="checkbox1" value="no" />
<input type="checkbox" name="checkbox1" value="yes" />

, ( , ) .

FILTER_VALIDATE_BOOLEAN.

, , formCheckbox ($ name), ( 'on' , ), ..

+6

<?php
//first part of the query
$query = "UPDATE table SET ";

$howManyCheckboxes = 5;
//for every checkbox , see if it exist , if it is, add it to the query
for($i=1;$i<=$howManyCheckboxes;$i++)
{
   if(isset($_POST['checkbox'.$i]))
   {
      $query = $query . " checkbox".$i."='".escape($_POST['checkbox'.$i])."',";
   }
}
//lets remove the last coma
$query = substr($query,0,-1);
//add the rest of the query
$query = $query . " LIMIT 1";

$result = mysql_query( $query );
if( ! $result ) echo "um, not everything went as expected.";
?>
0

Source: https://habr.com/ru/post/1706370/


All Articles