如果或在PHP中使用else

时间:2012-03-15 20:54:16

标签: php

我刚开始学习一些关于PHP的知识;使用IF ||时遇到以下代码问题检查表单中的多个语句。这是我的代码;有人可以给我一些指示吗?

  <html>
<body>
<?php
if (((($_POST['first_name']== null) || ($_POST['last_name']== null) || ($_POST['email']== null) || ($_POST['comments']== null)))) {
echo "Error one or more fields have been left empty please complete all details marked with a *.";}

else {

echo $_POST['first_name']; <br />
echo $_POST['last_name']; <br />
echo $_POST['email']; <br />
echo $_POST['telephone']; <br />
echo $_POST['comments']; <br />
}
?>
</body>
</html>

4 个答案:

答案 0 :(得分:1)

使用此格式

<?php
if (((($_POST['first_name']== null) || ($_POST['last_name']== null) || ($_POST['email']==  null) || ($_POST['comments']== null)))) {
    echo "Error one or more fields have been left empty please complete all details marked with a *.";
}else{
    echo $_POST['first_name'], '<br />';
    echo $_POST['last_name'], '<br />';
    echo $_POST['email'], '<br />';
    echo $_POST['telephone'], '<br />';
    echo $_POST['comments'], '<br />';
}
?>

答案 1 :(得分:1)

你可能会更好:

if( !$_POST['first_name']) echo "You left the First Name blank";
elseif( !$_POST['last_name']) echo "You left the Last Name blank";
elseif( !$_POST['email']) echo "You left the Email blank";
elseif( !$_POST['telephone']) echo "You left the Telephone blank";
elseif( !$_POST['comments']) echo "You left the Comments blank";
else {
    // do magic here.
}

当然,您可以自定义错误消息,也可以执行一些操作,例如突出显示空白的框,以便用户更清楚地看到错过的内容。

答案 2 :(得分:1)

您没有正确关闭<br>代码。以下代码应该有效。

<html>
<body>
<?php
if (((($_POST['first_name']== null) || ($_POST['last_name']== null) || ($_POST['email']== null) || ($_POST['comments']== null)))) {
echo "Error one or more fields have been left empty please complete all details marked with a *.";}

else {

echo $_POST['first_name'];
echo "<br />";
echo $_POST['last_name'];
echo "<br />";
echo $_POST['email'];
echo "<br />";
echo $_POST['telephone'];
echo "<br />";
echo $_POST['comments'];
echo "<br />";
}
?>
</body>
</html>

答案 3 :(得分:0)

以下分号无效:

else; {
    ^--- invalid

它终止你的if()语句,导致else子句应该是它自己的独立代码块。