PHP MySQL插入文件,使用带有OR运算符的IF语句验证表单

时间:2015-04-25 18:36:24

标签: php mysql forms validation if-statement

我是PHP的新手,我不确定我的技术是不是很好的做法,但我的代码一直有效,直到我添加了if语句的|| (!is_numeric($variable))部分。

我通过在数字字段中插入字母来测试代码,但确保字符串的长度是正确的。当我这样做时,代码运行else语句和回声"。$ jname。"添加.....等""。 mysqli_query已注释掉以供测试。我尝试了不同的版本,或多或少的括号。

为什么不能is_numeric()抓住我的信件?我被允许做多个! if语句中的参数?

<?Php
    header('Refresh: 3; url=../job_table.php');
    require 'connect.php';  
    $jname = mysqli_real_escape_string($db,$_POST['field1']);
    $jname_length = 25;
    $jwo = mysqli_real_escape_string($db,$_POST['field2']);
    $jwo_length = 7;
    $jpo = mysqli_real_escape_string($db,$_POST['field3']);
    $jpo_length = 4;
    $add_job_query = "INSERT INTO jobs (name, wo_no, po_no) VALUES ('$jname','$jwo','$jpo')";
    if(($jname || $jwo || $jpo ) == "") {
        echo "<center><h1>Please fill all fields!</h1></center>";
    } elseif(!(strlen($jname) <= $jname_length)) {
        echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
    } elseif((strlen($jwo) != $jwo_length) || (!is_numeric($jwo))) {
        echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
    } elseif((strlen($jpo) != $jpo_length) || (!is_numeric($jwo))) {
        echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
    } else {
        //echo mysqli_query($db,$add_job_query);
        echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
    }
    echo "<center><h1>Please wait.</h1></center>";
?>

1 个答案:

答案 0 :(得分:0)

在我看来,你需要这样的东西。

if(empty($jname) || empty($jwo) || empty($jpo)){
    echo "<center><h1>Please fill all fields!</h1></center>";
}elseif($jname <= $jname_length){
    echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
}elseif(($jwo != $jwo_length) || (!is_numeric($jwo))){
    echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
}elseif(($jpo != $jpo_length) || (!is_numeric($jwo))){
    echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
}else{
    //echo mysqli_query($db,$add_job_query);
    echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
}