PHP - 完整表單



本章將表單驗證和提取 HTML 表單資料到 PHP 程式碼中的所有概念都整合在一起。下面給出的完整表單處理程式碼分為三個部分:開頭是一個 PHP 程式碼部分,用於在提交表單時查詢任何驗證錯誤,HTML 表單包含各種元素,如文字欄位、單選按鈕、選擇控制元件、複選框等。第三部分又是 PHP 程式碼,用於呈現使用者輸入的資料。

PHP 錯誤跟蹤

捕獲錯誤的程式碼位於整個指令碼的開頭。顯然,每次載入頁面時都會執行此程式碼。如果在提交表單後加載頁面,則以下部分檢查每個元素是否為空、電子郵件欄位格式是否正確以及是否選中了複選框(表示使用者同意條款)。

<?php

   // define variables and set to empty values
   $nameErr = $emailErr = $genderErr = $websiteErr = "";
   $name = $email = $gender = $class = $course = $subject = "";

   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["name"])) {
         $nameErr = "Name is required";
      } else {
         $name = test_input($_POST["name"]);
      }

      if (empty($_POST["email"])) {
         $emailErr = "Email is required";
      } else {
         $email = test_input($_POST["email"]);
		 
         // check if e-mail address is well-formed
         if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format"; 
         }
      }

      if (empty($_POST["course"])) {
         $course = "";
      } else {
         $course = test_input($_POST["course"]);
      }

      if (empty($_POST["class"])) {
         $class = "";
      } else {
         $class = test_input($_POST["class"]);
      }

      if (empty($_POST["gender"])) {
         $genderErr = "Gender is required";
      } else {
         $gender = test_input($_POST["gender"]);
      }

      if (empty($_POST["subject"])) {
         $subjectErr = "You must select one or more subjects";
      } else {
         $subject = $_POST["subject"];	
      }
   }

   function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
   }
?>

HTML 表單

呈現輸入表單的 HTML 指令碼位於錯誤捕獲程式碼之後。表單設計中使用了各種表單元素。

<h2>Absolute Classes Registration Form</h2>
<p><span class = "error">* required field.</span></p>
<form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   <table>
      <tr>
         <td>Name:</td>
         <td>
            <input type = "text" name = "name">
            <span class = "error">* <?php echo $nameErr;?></span>
         </td>
      </tr>
      <tr>
         <td>E-mail: </td>
         <td>
            <input type = "text" name = "email">
            <span class = "error">* <?php echo $emailErr;?></span>
         </td>
      </tr>
      <tr>
         <td>Time:</td>
         <td>
            <input type = "text" name = "course">
            <span class = "error"><?php echo $websiteErr;?></span>
         </td>
      </tr>
      <tr>
         <td>Classes:</td>
         <td><textarea name = "class" rows = "5" cols = "40"></textarea></td>
      </tr>
      <tr>
         <td>Gender:</td>
         <td>
            <input type = "radio" name = "gender" value = "female">Female
            <input type = "radio" name = "gender" value = "male">Male
            <span class = "error">* <?php echo $genderErr;?></span>
         </td>
      </tr>
      <tr>
         <td>Select:</td>
         <td>
            <select name = "subject[]" size = "4" multiple>
               <option value = "Android">C</option>
               <option value = "Java">Java</option>
               <option value = "C#">C#</option>
               <option value = "Data Base">C++</option>
               <option value = "Hadoop">PHP</option>
               <option value = "VB script">Python</option>
            </select>
         </td>
      </tr>
      <tr>
         <td>Agree</td>
         <td><input type = "checkbox" name = "checked" value = "1"></td>
         <?php if(!isset($_POST['checked'])){ ?>
            <span class = "error">* <?php echo "You must agree to terms";?></span>
         <?php } ?> 
      </tr>
      <tr>
         <td>
            <input type = "submit" name = "submit" value = "Submit"> 
         </td>
      </tr>
   </table>
</form>

請注意,表單資料會提交回同一個指令碼,因此表單的 action 屬性設定為 $_SERVER["PHP_SELF"] 超全域性變數。此部分還包含某些內聯 PHP 程式碼,這些程式碼會在相應的表單控制元件旁邊顯示錯誤訊息,例如,如果在提交表單時名稱欄位為空,則在名稱文字框旁邊顯示“名稱必填”訊息。

顯示錶單資料

指令碼的第三部分又是 PHP 程式碼,用於回顯使用者提交的每個表單欄位的值。

<?php
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      echo "<h2>Your given values are as :</h2>";
      echo ("<p><b>Name</b> : $name</p>");
      echo ("<p><b>Email address</b> : $email</p>");
      echo ("<p><b>Preffered class time</b> : $course</p>");
      echo ("<p><b>Class info</b> : $class </p>");
      echo ("<p><b>Gender</b> : $gender</p>");
      echo "<p><b>Subjcts Chosen:</b><p>";
      if (!empty($subject)) { 
         echo "<ul>";
         for($i = 0; $i < count($subject); $i++) {
            echo "<li>$subject[$i]</u/li>";
         }
         echo "</ul>";
      }
   }
?>

以下是當從伺服器的文件根資料夾執行指令碼時,在表單中填寫的一些示例資料:

PHP Complete Form 1

提交後,輸出如下所示:

PHP Complete Form 2

示例

PHP 處理 HTML 表單的完整程式碼如下:

<html>
<head>
   <style>
      .error {color: #FF0000;}
   </style>
</head>
<body>
   <?php
   
      // define variables and set to empty values
      $nameErr = $emailErr = $genderErr = $websiteErr = "";
      $name = $email = $gender = $class = $course = $subject = "";

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         if (empty($_POST["name"])) {
            $nameErr = "Name is required";
         }else {
            $name = test_input($_POST["name"]);
         }

         if (empty($_POST["email"])) {
            $emailErr = "Email is required";
         } else {
            $email = test_input($_POST["email"]);

            // check if e-mail address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
               $emailErr = "Invalid email format"; 
            }
         }

         if (empty($_POST["course"])) {
            $course = "";
         } else {
            $course = test_input($_POST["course"]);
         }

         if (empty($_POST["class"])) {
            $class = "";
         } else {
            $class = test_input($_POST["class"]);
         }

         if (empty($_POST["gender"])) {
            $genderErr = "Gender is required";
         } else {
            $gender = test_input($_POST["gender"]);
         }

         if (empty($_POST["subject"])) {
            $subjectErr = "You must select one or more subjects";
         } else {
            $subject = $_POST["subject"];	
         }
      }

      function test_input($data) {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
      }
   ?>
   <h2>Absolute Classes Registration Form</h2>
   <p><span class = "error">* required field.</span></p>
   <form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <table>
         <tr>
            <td>Name:</td>
            <td>
               <input type = "text" name = "name">
               <span class = "error">* <?php echo $nameErr;?></span>
            </td>
         </tr>
         <tr>
            <td>E-mail: </td>
            <td>
               <input type = "text" name = "email">
               <span class = "error">* <?php echo $emailErr;?></span>
            </td>
         </tr>
         <tr>
            <td>Time:</td>
            <td> 
               <input type = "text" name = "course">
               <span class = "error"><?php echo $websiteErr;?></span>
            </td>
         </tr>
         <tr>
            <td>Classes:</td>
            <td><textarea name = "class" rows = "5" cols = "40"></textarea></td>
         </tr>
         <tr>
            <td>Gender:</td>
            <td>
               <input type = "radio" name = "gender" value = "female">Female
               <input type = "radio" name = "gender" value = "male">Male
               <span class = "error">* <?php echo $genderErr;?></span>
            </td>
         </tr>
         <tr>
            <td>Select:</td>
            <td>
               <select name = "subject[]" size = "4" multiple>
                  <option value = "C">C</option>
                  <option value = "Java">Java</option>
                  <option value = "C#">C#</option>
                  <option value = "c++">C++</option>
                  <option value = "PHP">PHP</option>
                  <option value = "Python">Python</option>
               </select>
            </td>
         </tr>
         <tr>
            <td>Agree</td>
            <td><input type = "checkbox" name = "checked" value = "1"></td>
            <?php if(!isset($_POST['checked'])){ ?>
               <span class = "error">* <?php echo "You must agree to terms";?></span>
            <?php } ?> 
         </tr>
         <tr>
            <td>
               <input type = "submit" name = "submit" value = "Submit"> 
            </td>
         </tr>
      </table>
   </form>
   <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         echo "<h2>Your given values are as :</h2>";
         echo ("<p><b>Name</b> : $name</p>");
         echo ("<p><b>Email address</b> : $email</p>");
         echo ("<p><b>Preffered class time</b> : $course</p>");
         echo ("<p><b>Class info</b> : $class </p>");
         echo ("<p><b>Gender</b> : $gender</p>");
         echo "<p><b>Subjcts Chosen:</b><p>";
         if (!empty($subject)) { 
            echo "<ul>";
            for($i = 0; $i < count($subject); $i++) {
               echo "<li>$subject[$i]</u/li>";
            }
            echo "</ul>";
         }
      }
   ?>
</body>
</html>

它將產生以下輸出

PHP Complete Form 1
廣告

© . All rights reserved.