帮助PHP和HTML复选框

时间:2011-06-29 22:57:13

标签: php mysql forms checkbox

我需要使用Checkboxes和PHP的帮助。我只是想确定是否使用PHP检查复选框的值。

示例:

<?php
include ("inc/conf.php");
$id = $_SESSION['id'];

if(isset($_POST['subfrm'])){
  $gtid = $_REQUEST['tid'];

  $ch1 = $_REQUEST['ch1'];
  if($ch1 == "ON"){
    $gch1 = "Y";
  } else {
    $gch1 = "N";
  }

  $ch2 = $_REQUEST['ch2'];
  if($ch2 == "ON"){
    $gch2 = "Y";
  } else {
    $gch2 = "N";
  }

  mysql_query("UPDATE SET ctable ch1='$gch1', ch2='$gch2' WHERE id='$gtid'");
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="tid" value="<?php echo $id; ?>" />
<input type="checkbox" name="ch1" />Hats
<input type="checkbox" name="ch2" />Watches
<textarea name="thetext"></textarea>
<input type="submit" name="subfrm" value="PUNCH ME" />
</form>

3 个答案:

答案 0 :(得分:2)

试试这个:

<?php
$ch1 = isset($_REQUEST['ch1']);

如果未选中该复选框,则其相应的变量将不会显示在请求中。

答案 1 :(得分:2)

if(isset($_REQUEST["ch1"])){
    $gch1 = "Y";
} else {
    $gch1 = "N";
}
if(isset($_REQUEST["ch2"])){
    $gch2 = "Y";
} else {
    $gch2 = "N";
}

您无需检查该值是什么,因为如果未检查该值,它将不会提交任何数据,如果是,则会提交on的值。

答案 2 :(得分:0)

通过这一起。它会让您知道选中了哪个复选框,并且还会保留对表单提交的检查。

<?php
$message = '';
$ch1_checked = false;
$ch2_checked = false;
if(isset($_POST['submit_button'])) {
    // Form was submitted
    $ch1_checked = isset($_POST['ch1']);
    $ch2_checked = isset($_POST['ch2']);

    if($ch1_checked && $ch2_checked) {
        $message .= 'Both were checked.';
    } else if($ch1_checked) {
        $message .= 'Checkbox 1 was checked.';
    } else if($ch2_checked) {
        $message .= 'Checkbox 2 was checked.';
    } else {
        $message .= 'Neither were checked.';
    }
}
?>

<?php echo $message; ?>
<form id="my_form" action="test.php" method="post">
    <input type="checkbox" name="ch1" value="ch1" <?php if($ch1_checked) echo 'checked'; ?> />Checkbox 1<br />
    <input type="checkbox" name="ch2" value="ch2" <?php if($ch2_checked) echo 'checked'; ?> />Checkbox 2<br />
    <input type="submit" name="submit_button" value="Go!" />
</form>