0
所以我想驗證一個窗體的PHP。問題與我的foreach循環
我的聯繫方式是典型的形式
<form method="post" action="contact.php">
<table class="contact">
<tr>
<th>
<label for="name">Name</label>
</th>
<td>
<input type="text" name="name" id="name">
</td>
</tr>
<tr>
<th>
<label for="email">Email</label>
</th>
<td>
<input type="text" name="email" id="email">
</td>
</tr>
<tr>
<th>
<label for="message">Message</label>
</th>
<td>
<textarea name="message" id="message"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Send">
現在我想的PHP驗證添加到這個,所以我創建了以下:
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(empty($name) === true || empty($email) === true || empty($message) === true) {
$errors[] = 'Please fill out all the required forms!';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Sorry please enter a valid email address';
}
if (ctype_alpha($name) === false) {
$errors[] = 'Sorry, name must contain only letters!';
}
}
print_r ($errors);
現在我試着打印這和數組顯示的數據被歸入字段,所有的驗證正常工作。我遇到的問題是下一步,我添加PHP來回顯列表中的數組。
形式上面,我添加的代碼是一個foreach循環是假設列出被證明進行驗證的任何失敗的錯誤:
<?php
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li>' , $error ,'</li>';
}
echo '</ul>';
}
?>
但現在的問題是這樣的:每次我現在填寫錯誤形式不產生一個列表,他們只是產生原始數組,如果沒有看到foreach。
任何建議或幫助將是偉大的!
謝謝你們,
鋪設出一個HTML表格形式不是「典型」。那麼......也許十年前。 :) – keyboardSmasher
您應該將'=== false'更改爲popnoodles具有或使用!empty。 – Celeritas
關於表格中的表格的事情是,對齊輸入的標記少於對錶格的另一種方式,以及您何時不希望這些字段以表格方式表現?不使用表格進行佈局是絕對正確的,但是對於輸入之後需要輸入的表單來說,這些表單完全沒問題,它們都需要很好地排列,就像切斷你的鼻子來貶低你的臉。 – Popnoodles