我的联系表格有一点问题。我想我做对了一切,但我总是得到同样错误的结果。
这是我的代码:
<?php
if (isset($_POST['contact_name']) && isset($_POST['contact_email']) && isset($_POST['contact_message'])) {
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_message = $_POST['contact_message'];
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_message)) {
echo '0K!';
} else {
echo 'Every field is required.';
}
}
?>
<form action="contacts.php" method="POST">
Nome:<br><input type="text" name="contact_name" maxlength="25"><br><br>
Email:<br><input type="text" name="contact_email" maxlength="50"><br><br>
Mensagem:<br>
<textarea name="contact_message" rows="6" cols="30" maxlength="1000"></textarea><br><br>
<input type="submit" value="Enviar">
</form>
当我填写所有字段时,我得到相同的结果"每个字段都是必填的",而它应该显示"OK!但我知道所有字段都收到了我写的内容,因为我之前测试过。
我知道这是一个基本问题,但我无法弄清楚。
错误是:!empty($contact_mensagem)
(消息已由 halfer 编辑),但您实际上有 $contact_message
.我已经在我的计算机上尝试了代码,它起作用了:
<?php
if (isset($_POST['contact_name']) && isset($_POST['contact_email']) && isset($_POST['contact_message'])) {
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_message = $_POST['contact_message'];
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_message)) {
echo '0K!';
} else {
echo 'Every field is required.';
}
}
?>
<form action="contacts.php" method="POST">
Nome:<br><input type="text" name="contact_name" maxlength="25"><br><br>
Email:<br><input type="text" name="contact_email" maxlength="50"><br><br>
Mensagem:<br>
<textarea name="contact_message" rows="6" cols="30" maxlength="1000"></textarea><br><br>
<input type="submit" value="Enviar">
</form>
试试这个:
<?php
if(isset($_POST['submit'])) {
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_message = $_POST['contact_message'];
if (empty($contact_name) && empty($contact_email) && empty($contact_message)) {
echo 'Every field is required.'; //This would be the message if the field(s) are empty.
} else {
echo 'OK!'; //This would be the message if all the fields are filled in.
}
}
?>
<form action="contacts.php" method="POST">
Nome:<br><input type="text" name="contact_name" maxlength="25"><br><br>
Email:<br><input type="text" name="contact_email" maxlength="50"><br><br>
Mensagem:<br>
<textarea name="contact_message" rows="6" cols="30" maxlength="1000"></textarea><br><br>
<input type="submit" value="Enviar" name="submit">
</form>
您的外部if
是多余的。这些将仅在 POST 操作期间设置,但无论它们是否完整,它们都将为每个 POST 设置,因为您的表单元素将始终提供一个值。所以,只需使用这个:
if ($_POST) {
接下来,以在索引不存在时不会引发警告的方式读取值:
$contact_name = isset($_POST['contact_name']) ? $_POST['contact_name'] : null;
$contact_email = isset($_POST['contact_email']) ? $_POST['contact_email'] : null;
$contact_message = isset($_POST['contact_message']) ? $_POST['contact_message'] : null;
然后,您可以像这样进行简单的测试:
if ($contact_name && $contact_email && $contact_message) {
// ok
}