PHP完整表單例項

本章節將介紹如何讓使用者在點選"提交(submit)"按鈕提交資料前保證所有欄位正確輸入。


PHP - 在表單中確保輸入值

在使用者點選提交按鈕後,為確保欄位值是否輸入正確,我們在HTML的input元素中插新增PHP指令碼, 各欄位名為: name, email, 和 website。 在備註中的 textarea 欄位中,我們將指令碼放於 <textarea> 和 </textarea> 標籤之間。

PHP指令碼輸出值為: $name, $email, $website, 和 $comment 變數。 

然後,我們同樣需要檢查被選中的單選按鈕, 對於這一點,我們 必須設定好checked屬性(不是radio按鈕的 value 屬性) :

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   名字: <input type="text" name="name" value="https://www.itread01.com/php/">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   E-mail: <input type="text" name="email" value="https://www.itread01.com/php/">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   網址: <input type="text" name="website" value="https://www.itread01.com/php/">
   <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   備註: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
   <br><br>
   性別:
   <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>  value="https://www.itread01.com/php/female">女
   <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>  value="https://www.itread01.com/php/male">男
   <span class="error">* <?php echo $genderErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="https://www.itread01.com/php/Submit"> 
</form>

PHP - 完整表單例項

以下是完整的PHP表單驗證例項程式碼:

例項


執行例項 ?

例項中執行結果類似如下圖所示: