How to read if a checkbox is checked in PHP?

后端 未结 18 955
刺人心
刺人心 2020-11-22 07:54

How to read if a checkbox is checked in PHP?

相关标签:
18条回答
  • 2020-11-22 08:44
    $is_checked = isset($_POST['your_checkbox_name']) &&
                  $_POST['your_checkbox_name'] == 'on';
    

    Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.

    0 讨论(0)
  • 2020-11-22 08:46

    If your HTML page looks like this:

    <input type="checkbox" name="test" value="value1">
    

    After submitting the form you can check it with:

    isset($_POST['test'])
    

    or

    if ($_POST['test'] == 'value1') ...
    
    0 讨论(0)
  • 2020-11-22 08:46

    in BS3 you can put

      <?php
                      $checked="hola";
                      $exenta = $datosOrdenCompra[0]['exenta'];
                      var_dump($datosOrdenCompra[0]['exenta']);
                      if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
    
                          $checked="on";
    
                      }else{
                        $checked="off";
                      }
    
                  ?>
                  <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
    

    Please Note the usage of isset($datosOrdenCompra[0]['exenta'])

    0 讨论(0)
  • 2020-11-22 08:48

    I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

    HTML Code: (for Add Page)

    <input name="status" type="checkbox" value="1" checked>
    

    Hint: remove "checkbox" if you want to show it as unchecked by default

    HTML Code: (for Edit Page)

    <input name="status" type="checkbox" value="1" 
    <?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
    

    PHP Code: (use for Add/Edit pages)

    $status = $_POST['status'];
    if ($status == 1) {
    $status = 1;
    } else {
    $status = 0;
    }
    

    Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.

    0 讨论(0)
  • 2020-11-22 08:53

    A minimalistic boolean check with switch position retaining

    <?php
    
    $checked = ($_POST['foo'] == ' checked');
    
    ?>
    
    <input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
    
    0 讨论(0)
  • 2020-11-22 08:53
    <?php
    
    if(isset($_POST['nameCheckbox'])){
        $_SESSION['fr_nameCheckbox'] = true;
    }
    
    ?>
    
    <input type="checkbox" name="nameCheckbox" 
    
    <?php 
    
    if(isset($_SESSION['fr_nameCheckbox'])){
        echo 'checked'; 
        unset($_SESSION['fr_nameCheckbox']);
    } 
    
    ?>
    
    0 讨论(0)
提交回复
热议问题