0

I'm having a problem with my php code.

I don't want the else echo "Check it again!"; to show unless they input some data into the form(input box) and it's not valid. But when I load the page it shows the error above the box.

<?PHP
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    mysql_query("INSERT INTO newsletter (email) VALUES('$email')") or die(mysql_error());
        echo 'You have registered your E-Mail address to our database! You will now receive regular updates on the progess!';
    }else{
        echo "Check it again!";
}
?>

<form name="newsletter" method="post" action="<?PHP $_SERVER['PHP_SELF']?>">
<input type="text" name="newsletter" id="newsletter">
<input type="submit" value="SUBMIT!">
</form>
4

2 回答 2

2

尝试这个 :)

<?PHP
if($_SERVER["REQUEST_METHOD"]=="POST"){
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        mysql_query("INSERT INTO newsletter (email) VALUES('$email')") or die(mysql_error());
            echo 'You have registered your E-Mail address to our database! You will now receive regular updates on the progess!';
        }else{
            echo "Check it again!";
    }
}
?>

代替

<?PHP

 if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    mysql_query("INSERT INTO newsletter (email) VALUES('$email')") or die(mysql_error());
    echo 'You have registered your E-Mail address to our database! You will now receive regular updates on the progess!';
    }else{
      echo "Check it again!";
    }
}

?>

编辑背后的逻辑:我们将检查电子邮件或打印“再次检查!” 仅当提交表单时。现在如果我们不检查表单是否提交或者这是第一次加载(或简单刷新)页面,要么插入,要么出现错误显示。我们不希望这样:)

于 2013-07-08T23:06:02.587 回答
0

这只是我喜欢的@MuhammedHedayet 答案的替代方案,仅在需要时才检查。两者都应该完美地工作:

<?PHP
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    mysql_query("INSERT INTO newsletter (email) VALUES('$email')") or die(mysql_error());
        echo 'You have registered your E-Mail address to our database! You will now receive regular updates on the progess!';
    } else if ($_SERVER["REQUEST_METHOD"]=="POST"){
        echo "Check it again!";
}
?>

<form name="newsletter" method="post" action="<?PHP $_SERVER['PHP_SELF']?>">
<input type="text" name="newsletter" id="newsletter">
<input type="submit" value="SUBMIT!">
</form>
于 2013-07-08T23:25:09.660 回答