使用单选按钮

时间:2013-02-15 22:23:00

标签: php html radio-button

我正在使用我的单选按钮进行安全检查,即使我认为不应该,也会返回错误。知道我做错了吗?

这是要更新的课程

public function set ($iStatus)
{
    $this->iStatus = $iStatus;
}
public function create ()
{
    if ($this->iStatus != 0 || $this->iStatus != 1 || $this->iStatus != 2)
    {
        echo "Your idea must have a valid status";
    }
    else
    {
        //update the database
    }
}

然后是html表单

if (isset($_POST["submit"]))
{
    $class->set($_POST["status"]);
    $class->create();
}
else
{
    <input type="radio" name="status" value="0" checked/> 
    <input type="radio" name="status" value="1" /> 
    <input type="radio" name="status" value="2" /> 
}

并返回错误有效状态。我想可能输入将所有内容保存为字符串或字符,所以我重新编写错误检查说

if ($this->iStatus != '0') { /*blah*/ }

但这也不起作用。所以我很困惑

2 个答案:

答案 0 :(得分:1)

错误在if语句中。你应该替换||与&amp;&amp;

否则您将始终收到错误消息

因为即使它为0,你的if语句也会返回true,因为!= 1是真的

答案 1 :(得分:1)

你的逻辑是倒退的:

if ($this->iStatus != 0 || $this->iStatus != 1 || $this->iStatus != 2)

应该是:

if ($this->iStatus != 0 && $this->iStatus != 1 && $this->iStatus != 2)

完整测试:

<?php
class foo{
    private $iStatus;

    public function set($iStatus){
        $this->iStatus = $iStatus;
    }
    public function create(){
        if ($this->iStatus != 0 && $this->iStatus != 1 && $this->iStatus != 2){
            echo "Your idea must have a valid status";
        }else{
            echo "All good";
        }
    }
}

if (isset($_POST["submit"])){
    $class = new foo;
    $class->set($_POST["status"]);
    $class->create();
}else{
    echo '
    <form method="post" action="./">
    <input type="radio" name="status" value="0" checked>
    <input type="radio" name="status" value="1"> 
    <input type="radio" name="status" value="2">
    <input type="radio" name="status" value="3">
    <input name="submit" type="submit">
    </form>';
}?>