简体   繁体   English

为什么即使我已经在其中添加了一些显示错误消息,零值仍然可以提交?

[英]Why the zero value still can submit even I already add some display error message there?

This is my code. 这是我的代码。 I already set the display error message in PHP code. 我已经在PHP代码中设置了显示错误消息。 But it looks like the display error message not working when all of the element is empty. 但是,当所有元素都为空时,似乎显示错误消息不起作用。 It can submit the empty value in a database. 它可以在数据库中提交空值。

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>


<p><span class="error">* required field.</span></p>
<form method="post" action="add.php<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">  
</form>

</body>
</html>

Here is my form action code add.php 这是我的表单操作代码add.php

<?php

mysql_connect("localhost","root","") or die("Cannot connect");
mysql_select_db("testingdb");


$name= $_POST['name'];
$email = $_POST['email'];
$website =$_POST['website'];
$comment=$_POST['comment'];
$gender=$_POST['gender'];

$result=mysql_query("INSERT INTO information (name , email, website, comment, gender) VALUES ('$name' , '$email' , '$website' , '$comment' , '$gender')");


if($result){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('SUCCESSFULLY ADD!') 
</SCRIPT>");
}
else {
    echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('FAILED TO ADD!')
</SCRIPT>");
}

?>

Well You never end up validating your form because your form will be submitted to add.php rather than the page containing validation rules it self. 好吧,您永远不会最终验证您的表单,因为您的表单将被提交到add.php而不是包含其自身的验证规则的页面。 So below is shown what you should do: 因此,下面显示了您应该做什么:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
$error=false; // set error state to false

//if its a post request
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }


    //validation rules
    if (empty($_POST["name"])) {
        $error=true;
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
    }

    if (empty($_POST["email"])) {
        $error=true;
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
    }

    if (empty($_POST["website"])) {
        $website = "";
    } else {
        $website = test_input($_POST["website"]);
    }

    if (empty($_POST["comment"])) {
        $comment = "";
    } else {
        $comment = test_input($_POST["comment"]);
    }

    if (empty($_POST["gender"])) {
        $error=true;
        $genderErr = "Gender is required";
    } else {
        $gender = test_input($_POST["gender"]);
    }

    //eof of validation rules


    //if there is no errors
    if(!$error){
        // connect to database and do your stuffs
        mysql_connect("localhost","root","") or die("Cannot connect");
        mysql_select_db("testingdb");


        $name= $_POST['name'];
        $email = $_POST['email'];
        $website =$_POST['website'];
        $comment=$_POST['comment'];
        $gender=$_POST['gender'];

        $result=mysql_query("INSERT INTO information (name , email, website,comment, gender) VALUES ('$name' , '$email' , '$website' , '$comment' , '$gender')");


        if($result){
            echo ("<SCRIPT LANGUAGE='JavaScript'>window.alert('SUCCESSFULLY ADD!')</SCRIPT>");
        }
        else {
            echo ("<SCRIPT LANGUAGE='JavaScript'>window.alert('FAILED TO ADD!')</SCRIPT>");
        }
    }else{  
    //show the forms with errors 
?>
<!DOCTYPE HTML>  
<html>
    <head>
        <style>
            .error {color: #FF0000;}
        </style>
    </head>
    <body> 
        <p><span class="error">* required field.</span></p>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
        Name: <input type="text" name="name">
        <span class="error">* <?php echo $nameErr;?></span>
        <br><br>
        E-mail: <input type="text" name="email">
        <span class="error">* <?php echo $emailErr;?></span>
        <br><br>
        Website: <input type="text" name="website">
        <span class="error"><?php echo $websiteErr;?></span>
        <br><br>
        Comment: <textarea name="comment" rows="5" cols="40"></textarea>
        <br><br>
        Gender:
        <input type="radio" name="gender" value="female">Female
        <input type="radio" name="gender" value="male">Male
        <span class="error">* <?php echo $genderErr;?></span>
        <br><br>
        <input type="submit" name="submit" value="Submit">  
    </form>

</body>
</html>
<?php
    }
}
?>

There is nothing stopping the form from being submitted, even if you add custom error messages to it. 即使您向表单添加自定义错误消息,也无法阻止表单的提交。 HTML is not advanced enough to identify error messages you have added and so the form will submit as normal. HTML不够先进,无法识别您添加的错误消息,因此该表单将按常规提交。

You are testing if $result is truth. 您正在测试$result是否为真。 If it is then you display the success message. 如果是,则显示成功消息。

What makes you believe a empty value will set $result to a false value? 是什么使您相信空值会将$result设置$result错误值? Are you expecting the database to return a false value? 您是否期望数据库返回false值?

You need to add more validation of the value/s you are passing to the database before you pass them if you what to avoid passing an empty value. 如果要避免传递空值,则需要在传递给数据库之前对传递的值进行更多验证。

There are a number of problems with the way in which you're attempting to insert the data, but I believe the reason that you're not having any output is because standard mysql commands are deprecated as of PHP 5.5, and removed as of PHP 7.0. 您尝试插入数据的方式有很多问题,但是我相信您没有任何输出的原因是因为自PHP 5.5起不推荐使用标准mysql命令,并自PHP起取消了该操作7.0。 Instead, you should be using MySQLi, or preferably, PDO. 相反,您应该使用MySQLi,或者最好使用PDO。 You'll need to restructure you code to use either, and I recommend reading up a bit on them first. 您需要重组代码以使用其中任何一种,我建议您先阅读一些内容。

See http://php.net/manual/en/mysqli.query.php and http://php.net/manual/en/class.pdo.php for further instructions on how to use them. 有关如何使用它们的更多说明,请参见http://php.net/manual/en/mysqli.query.phphttp://php.net/manual/en/class.pdo.php PDO is more secure, but harder to learn, and not all web hosts support it -- make sure to check with your hosting provider! PDO更安全,但更难学习,并且并非所有的Web主机都支持它-请务必与您的托管服务提供商联系!

One thing both methods push heavily is prepared queries. 两种方法都大力推动的一件事是准备好的查询。 Without using a prepared query, you're leaving yourself vulnerable to SQL injection. 如果不使用准备好的查询,您将容易受到SQL注入的攻击。 A prepared query binds the parameters being passed through, so they can't be manipulated. 准备好的查询绑定了要传递的参数,因此无法对其进行操作。

Here's a sample MySQLi prepared statement: 这是一个示例MySQLi准备的语句:

 if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
     $insert_stmt->bind_param('sss', $username, $email, $password);
     if (!$insert_stmt->execute()) {
         // Insert failed
     }
     // Insert was successful
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使我输入正确,它仍然显示错误警报消息 - Even if I give the right Input it still showing the error alert message 语法错误 - 即使我已经找到了错误,但错误仍然存在 - Sytax error - Even though I have already found the bug but the error still there 用户提交表单后如何显示成功消息 - How can I display a success message after the user submit the form 我需要帮助。 为什么我会收到此 JavaScript 错误消息,我该如何解决? - I need some help. Why do i get this JavaScript error message and how can i fix this? 如何检查数据库中已经存在的名字并给出错误消息? - How can i check firstname already in the database and give a error message? 我在firebug中收到一个未定义的错误,即使我可以看到该值存在! - I get an undefined error in firebug , even if I can see the value exists!…why? 即使我已经通过事件对其进行了更改,alert($(“#myHTMLElement”))为什么仍显示其原始属性? - Why does alert($(“#myHTMLElement”)) display its original properties even though I already mutated it via an event? 验证程序给出错误信息,但仍允许表单提交 - Validator gives error message, but still lets the form submit 即使Google图表中的值为零,如何显示小条? - How to display a small bar even when a value is zero in Google Charts? 单击提交按钮时,它只会刷新页面。 如何获得显示我想要的消息的信息? - When clicking on the submit button it just refreshes the page. How can I get it to display the message I desire?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM