PHP form checkbox and undefined index

前端 未结 3 741
醉话见心
醉话见心 2021-01-20 16:51

I am getting an \"Undefined index\" error when submitting a form with an un-checked checkbox. Is there any other way besides running an \"isset\" or \"empty\" check on each

相关标签:
3条回答
  • 2021-01-20 17:30

    If you want a on/off checkbox you can write a hidden value before you write the checkbox.

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

    This will always return a value, either no (default unless checkbox is checked by default) or yes.

    You can validate input with the filter functions with FILTER_VALIDATE_BOOLEAN.

    Its easier if you write a function for this, like formCheckbox($name), with options for values (value 'on' means checkbox is checked by default), attributes, etc.

    0 讨论(0)
  • try the following

    <?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 讨论(0)
  • 2021-01-20 17:31

    You could write a function that checks whether a checkbox was checked:

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

    Now call that function in your query like this:

    $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";
    
    0 讨论(0)
提交回复
热议问题