如何在我想要的地方回显错误消息


How to echo an error message in the place that I want

>我在下面有一个 if else 语句,它将查看数据库并在电子邮件不在数据库中时显示错误。我想回显提交按钮旁边的错误消息。目前,我的错误消息将始终出现在页面顶部。

if (mysql_num_rows($search_user_email) > 0) {
    echo "<p style='"color:red'"><b>Email found!</b></p>";
}
else {
echo "<p style='"color:red'"><b>Email not found!</b></p>";
}

<tr style="background-color: #FFFFFF; height: 18px">
<td>
<span style="font-size:10pt;">Search by email:</span>
</td>
<td>
<form action="" method="post" name="search_email_form">
<input type="text" style="height:15px; font-size:10pt;" name="search_email_input"></input>
</td>
<td>
<input type="submit" style="height:22px; font-size:10pt;" name="search_email_submit" value="Search"></input>
</form>

只需将错误消息保存到变量中并根据需要显示即可:

$errMsg="";
if (mysql_num_rows($search_user_email) > 0) {
    $errMsg= "<p style='"color:red'"><b>Email found!</b></p>";
}
else {
$errMsg= "<p style='"color:red'"><b>Email not found!</b></p>";
}

<tr style="background-color: #FFFFFF; height: 18px">
<td>
<span style="font-size:10pt;">Search by email:</span>
</td>
<td>
<form action="" method="post" name="search_email_form">
<input type="text" style="height:15px; font-size:10pt;" name="search_email_input"></input>
</td>
<td>
<input type="submit" style="height:22px; font-size:10pt;" name="search_email_submit" value="Search"></input>
</form><?php echo $errMsg; ?>
如果

出现错误,则设置一个标志

if (mysql_num_rows($search_user_email) > 0) {
    $emailError = true;
}
else {
echo "<p style='"color:red'"><b>Email not found!</b></p>";
}

<tr style="background-color: #FFFFFF; height: 18px">
<td>
<span style="font-size:10pt;">Search by email:</span>
</td>
<td>
<form action="" method="post" name="search_email_form">
<input type="text" style="height:15px; font-size:10pt;" name="search_email_input"></input>
</td>
<td>
<input type="submit" style="height:22px; font-size:10pt;" name="search_email_submit" value="Search"></input>
<?php if($emailError)
    echo "<p style='"color:red'"><b>Email found!</b></p>";
    $emailError = false;
?>
</form>

这就是我会这样做的:

<?php
if(mysql_num_rows($search_user_email) > 0) {
    $message = '<p style="color:red"><b>Email found!</b></p>';
} else {
    $message = '<p style="color:red"><b>Email not found!</b></p>';
}
?>
<tr style="background-color: #FFFFFF; height: 18px">
<td>
<span style="font-size:10pt;">Search by email:</span>
</td>
<td>
<form action="" method="post" name="search_email_form">
<input type="text" style="height:15px; font-size:10pt;" name="search_email_input" />
</td>
<td>
<input type="submit" style="height:22px; font-size:10pt;" name="search_email_submit" value="Search" />
</form>
<?php
if(isset($message)) {
    echo $message;
}
?>

顺便说一下,PHP 不再支持 mysql_ 函数,它们迟早会被删除。

编辑:
你不需要放</input>,你可以这样做:

<input ... />