簡體   English   中英

PHP在未調用時顯示“錯誤”

[英]PHP showing else “error” when not called

我的PHP代碼有問題。

我不希望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!";
}
?>

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

嘗試這個 :)

<?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!";
    }
}

?>

編輯背后的邏輯:我們將檢查電子郵件或打印“再次檢查!” 只有提交表格。 現在,如果我們不檢查表單是否已提交或者這是第一次加載(或簡單刷新)頁面,則會發生插入或錯誤顯示。 我們不希望這樣:)

這只是我喜歡的樣式的@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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM