歡迎來到 PHP/MySQL 教程的第三天(也是最後一天)。前兩天我們已經掌握了安裝環境、基本語法、迴圈與資料庫互動。今天將介紹幾個實用的函數,讓開發流程更順暢,重點包括檔案包含(include/require)與伺服器端資料驗證。
「標頭檔」是指被主程式引入的外部檔案,常用於放置共用的 HTML 標頭、頁尾、資料庫連線設定或自訂函數。PHP 提供兩個函數:
if 區塊中)。<html><body>
<?php
include("emptyfile.inc"); // 檔案不存在
echo "Hello World";
?>
</body></html>
將 include 改為 require 後重新執行,觀察輸出差異。
建議標頭檔副檔名用 .inc 區分,但務必在 Web 伺服器設定將 .inc 視為 PHP 處理,否則駭客可直接瀏覽原始碼(可能洩露資料庫密碼等敏感資訊)。
header.inc
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb", $db);
?>
<html><head><title><?php echo $title ?></title></head><body>
<center><h2><?php echo $title ?></h2></center>
footer.inc
<p>版權所有 © 2024</p>
</body></html>
主程式
<?php
$title = "Hello World";
include("header.inc");
$result = mysql_query("SELECT * FROM employees", $db);
echo "<table border=1>\n";
echo "<tr><td>名字</td><td>職位</td></tr>\n";
while ($myrow = mysql_fetch_row($result)) {
printf("<tr><td>%s %s</td><td>%s</td></tr>\n", $myrow[1], $myrow[2], $myrow[3]);
}
echo "</table>\n";
include("footer.inc");
?>
注意:$title 在 include("header.inc") 之前定義,標頭檔即可存取其值。這樣每個頁面只需設定 $title 即可複用模板。
使用者輸入不可信,必須在伺服器端驗證(客戶端 JS 可繞過)。常見規則:必填、長度、格式(如 Email 必含 @)、型別(數字欄位不接受文字)。
if (strlen($first) < 6 || strlen($last) < 6) {
$error = "姓名長度至少 6 個字元!";
}
可處理複雜模式比對,如 Email 格式、電話號碼等。此處略過詳細語法,建議參考專門正規表示式教材。
<html><body>
<?php
if ($submit) {
if (strlen($first) < 6 || strlen($last) < 6) {
$error = "對不起,您必須填寫所有欄位且長度至少 6 碼!";
} else {
echo "謝謝!資料已送出。";
}
}
if (!$submit || $error) {
echo $error;
?>
<p>
<form method="post" action="<?php echo $PHP_SELF ?>">
第一欄: <input type="text" name="first" value="<?php echo $first ?>"><br>
第二欄: <input type="text" name="last" value="<?php echo $last ?>"><br>
<input type="Submit" name="submit" value="送出">
</form>
<?php } ?>
</body></html>
關鍵點:巢狀 if 先檢查是否送出,再驗證變數內容。|| 為邏輯「或」,! 為「非」。
include 實現模板化,提升維護性。strlen、preg_match 是基礎工具。