如何检查是否已检查特定单选按钮

时间:2014-05-03 21:18:51

标签: php

我正在努力寻找这个令人沮丧的问题的解决方案。我正在尝试制作一个简单的程序来检查您希望cookie持续多长时间。如果我为单选按钮使用不同的名称,它工作正常。但显而易见的问题是用户可以选择多个选项。如何使用相同的名称并仍然检查是否已选择特定的名称? (以下代码)。

<?php


if(isset($_POST['submit'])){
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['secs']) && $_POST['secs'] == '5secs'){
    $UN = htmlentities($_POST['username']);
    setcookie('username',$UN,time()+5);
    header('Location: http://localhost/Learning/LearningMore/testing.php');
}else if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['secs']) && $_POST['secs'] == '10secs'){
    $UN = htmlentities($_POST['username']);
    setcookie('username',$UN,time()+10);
    header('Location: http://localhost/Learning/LearningMore/testing.php');
}else{
    echo 'Please fill out the whole form.';
}

}
?>

<form action="index.php" method="POST">
    Username: <input type="text" name="username"/>
    </br>
    5 Seconds: <input type="radio" name="secs" id="5secs"/> 10 Seconds: <input type="radio" name="secs" id="10secs"/>
    </br></br>
    <input type="submit" value="Submit" name="submit"/>
</form>

1 个答案:

答案 0 :(得分:0)

为了使当前的PHP代码有效,您需要设置您要查找的value

if(... $_POST['secs'] == '5secs'){
// expects value "5secs"
} else if (... $_POST['secs'] == '10secs'){
// expects value "10secs"

您可以像设置value s:

一样
5 Seconds: <input type="radio" name="secs" id="5secs" value="5secs"/>
10 Seconds: <input type="radio" name="secs" id="10secs" value="10secs"/>

顺便说一句,你可以在那里缩短你的条件。 empty()还检查是否设置了变量,因此isset()是多余的。另外两个secs个案例都需要设置$_POST['secs']且非空,所以为什么不组合if?然后只剩下一个比较,您可以使用漂亮的switch()

if (isset($_POST['submit'])) {
    if (!empty($_POST['username']) && !empty($_POST['secs'])) {
        switch ($_POST['secs']) {
            case "5secs":
                //...
                break;
            case "10secs":
                //...
                break;
            }
        }
    }
} else {
    echo 'Please fill out the whole form.';
}

通过这种方式,您可以在将来轻松修改代码 - 例如,当您想要进行其他选择时。只需添加另一个案例就可以了 - 如果要忘记等等,也不会有其他情况。

相关问题