3 文件 + 1 數據表:mysql.inc.php (配置) + install.php (建表) + index.php (主邏輯)。
<?php
$host = 'localhost';
$user = 'database_user_name';
$password = 'database_user_password';
$name = 'database_name';
?>
<?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>
<?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>
htmlspecialchars()mysql_real_escape_string()(生產請用 PDO 預處理)LIMIT offset, 20 + AJAX 載入更多重要:
mysql_*函數已棄用,新項目請使用 PDO 或 MySQLi。本教程為教學演示。