PHP复选框 - 返回'是'而不是1如何?

时间:2011-07-27 12:24:11

标签: php syntax checkbox

我有一个带有复选框的简单联系表格,一旦有效并提交,我就会回复表格的结果。我希望复选框项目如果选中则返回YES,如果空白则返回NO。

这是我的代码:

 $subject = "Website Contact Form Enquiry";

//If the form is submitted
if(isset($_POST['submit'])) {

    //Check to make sure that the name field is not empty
    if(trim($_POST['contactname']) == '') {
        $hasError = true;
    } else {
        $name = trim($_POST['contactname']);
    }

    //Check to make sure sure that a valid email address is submitted
    if(trim($_POST['email']) == '')  {
        $hasError = true;
    } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    //Check to make sure comments were entered
    if(trim($_POST['message']) == '') {
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $comments = stripslashes(trim($_POST['message']));
        } else {
            $comments = trim($_POST['message']);
        }
    }

    if(isset($_POST['tour']) &&
       $_POST['tour'] == 'yes')
    {
        $tour = true;
    }
    else
    {
        $tour = false;
    } 

    //If there is no error, send the email
    if(!isset($hasError)) {
        $emailTo = 'info@bgv.co.za'; //Put your own email address here
        $body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
        $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;

    }
}

继承人回声

        <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
        <div id="sadhu">
        <p class="general_site">Name:</p><p class="general_siter"><strong><?php echo $name;?></strong></p>
        <p class="general_site">Email:</p><p class="general_siter"><strong><?php echo $email;?></strong></p>
        <p class="general_site">Message:</p><p class="general_siter"><strong><?php echo $comments;?></strong></p>
        <p class="general_site">Tour:</p><p class="general_siter"><strong><?php echo $tour;?></strong></p>
        </div>
        <?php } ?>

5 个答案:

答案 0 :(得分:0)

您无法控制客户返回给您的值。如果他们返回0或1而不是是或否,您可以将其翻译为:

echo ($name == 1) ? "Yes" : "No

这是三元运营商;它允许您根据条件($ name == 0)是否为真来返回不同的值。

答案 1 :(得分:0)

我认为你可以做(​​但我猜是因为它不清楚复选框是什么元素):

if(isset($_POST['tour']) &&
   $_POST['tour'] == 'yes')
{
    $tour = 'Yes';
}
else
{
    $tour = 'No';
} 

在你的情况下,你回显1,因为你回显真正的whic转换为1或false,转换为0

答案 2 :(得分:0)

在您的表单中,复选框应具有值

<input type="checkbox" name="tour" value="yes"/>

所以在PHP中你应该做

if(isset($_POST['tour']) &&
   $_POST['tour'] == 'yes')
{
    $tour = "yes";
}
else
{
    $tour = "no";
} 

答案 3 :(得分:0)

到目前为止未提及的一件事是,如果未选中此框,您将无法获得任何价值! 你在html中设置的实际值如下:     

答案 4 :(得分:0)

复选框是布尔值。他们要么有价值,要么没有价值。他们实际拥有的价值是无关紧要的。您需要做的就是检查是否存在值,并采取相应措施。

$tour = isset($_POST['tour'])? 'Yes': 'No';