开发者

Help PHP and HTML Checkboxes

I need help working with Checkboxes and PHP. I'm just trying to determine a value on whether the checkbox is checked or not with PHP.

Example:

<?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>


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

You don't need to check to see what the value is, because it will not submit any data whatsoever if it isn't checked, and it will submit a value of on if it is.


Try this:

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

If the check box wasn't checked, its corresponding variable won't show up in the request.


Through this together. It will let you know which checkbox was selected and it will also retain the check on form submit.

<?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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜