首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP + MySQL 快速構建 ShoutBox(留言板)完整教程

     編輯:PHP 綜合知識

架構概覽

3 文件 + 1 數據表:mysql.inc.php (配置) + install.php (建表) + index.php (主邏輯)。

文件 1:mysql.inc.php

<?php
$host = 'localhost';
$user = 'database_user_name';
$password = 'database_user_password';
$name = 'database_name';
?>

文件 2:install.php(僅執行一次,隨後刪除)

<?php
include("mysql.inc.php");
$conn = @mysql_connect($host, $user, $password) or die(mysql_error());
$db = @mysql_select_db($name, $conn) or die(mysql_error());

// 重建表
mysql_query("DROP TABLE IF EXISTS `shouts`", $conn);
$sql = "CREATE TABLE `shouts` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `shoutby` VARCHAR(50) DEFAULT NULL,
    `shout` VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
mysql_query($sql, $conn) or die(mysql_error());
echo "Table 'shouts' created successfully.";
?>
<html><body>
安裝完成,請立即刪除 install.php。<br>
<a href="index.php">進入 ShoutBox</a>
</body></html>

文件 3:index.php(核心邏輯)

<?php
include("mysql.inc.php");
$conn = @mysql_connect($host, $user, $password) or die(mysql_error());
$db = @mysql_select_db($name, $conn) or die(mysql_error());
mysql_query("SET NAMES utf8", $conn);

// 處理發布
if ($_POST['shout'] && $_POST['shoutby']) {
    $by = mysql_real_escape_string($_POST['shoutby']);
    $msg = mysql_real_escape_string($_POST['shout']);
    mysql_query("INSERT INTO shouts (shoutby, shout) VALUES ('$by', '$msg')", $conn);
}

// 讀取最新 20 條
$res = mysql_query("SELECT * FROM shouts ORDER BY id DESC LIMIT 20", $conn);
$shouts = array();
while ($row = mysql_fetch_assoc($res)) $shouts[] = $row;
?>
<html>
<head><title>ShoutBox</title>
<style>
body{font:12px/1.5 Tahoma;max-width:600px;margin:20px auto;}
.shout{border-bottom:1px solid #eee;padding:10px 0;}
.shout .meta{color:#999;font-size:11px;}
.shout .msg{margin-top:5px;}
form{margin-top:20px;}
</style>
</head>
<body>
<h2>ShoutBox</h2>
<?php foreach ($shouts as $s): ?>
<div class="shout">
    <div class="meta"><?= $s['shoutby'] ?> @ <?= $s['timestamp'] ?></div>
    <div class="msg"><?= htmlspecialchars($s['shout']) ?></div>
</div>
<?php endforeach; ?>

<form method="post">
    暱稱: <input name="shoutby" size="15" maxlength="50" /><br>
    內容: <input name="shout" size="50" maxlength="255" /><br>
    <input type="submit" value="發布" />
</form>
</body></html>

安全與擴展提示

  • XSS 防護:輸出時 htmlspecialchars()
  • SQL 注入:入庫用 mysql_real_escape_string()(生產請用 PDO 預處理)
  • 防刷限制:Session/IP 限流、驗證碼
  • 分頁/無限滾動:LIMIT offset, 20 + AJAX 載入更多
  • 管理後台:刪除違規、封禁用戶、關鍵詞過濾

重要:mysql_* 函數已棄用,新項目請使用 PDO 或 MySQLi。本教程為教學演示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved