php实现文章
PHP实现文章管理功能
数据库设计
创建articles表存储文章数据,包含id、title、content、author、created_at等字段。使用MySQLi或PDO扩展连接数据库。
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
建立数据库连接配置文件config.php,包含数据库连接参数和PDO实例。
<?php
$host = 'localhost';
$dbname = 'article_db';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
文章创建功能
创建表单提交文章数据,后端处理并存入数据库。
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_POST['author'];
$stmt = $pdo->prepare("INSERT INTO articles (title, content, author) VALUES (?, ?, ?)");
$stmt->execute([$title, $content, $author]);
header("Location: index.php");
exit;
}
文章列表展示
从数据库查询文章数据并以列表形式展示。
$stmt = $pdo->query("SELECT * FROM articles ORDER BY created_at DESC");
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($articles as $article) {
echo "<h3>{$article['title']}</h3>";
echo "<p>{$article['content']}</p>";
echo "<small>作者: {$article['author']} | 发布时间: {$article['created_at']}</small>";
}
文章编辑功能
提供编辑表单并更新数据库记录。
// 获取要编辑的文章
$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM articles WHERE id = ?");
$stmt->execute([$id]);
$article = $stmt->fetch();
// 更新文章
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
$stmt = $pdo->prepare("UPDATE articles SET title = ?, content = ? WHERE id = ?");
$stmt->execute([$title, $content, $id]);
header("Location: index.php");
exit;
}
文章删除功能
从数据库删除指定文章记录。
$id = $_GET['id'];
$stmt = $pdo->prepare("DELETE FROM articles WHERE id = ?");
$stmt->execute([$id]);
header("Location: index.php");
exit;
安全防护措施
对用户输入进行过滤和验证,防止SQL注入和XSS攻击。
// 过滤输入
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
$content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
// 预处理语句防止SQL注入
$stmt = $pdo->prepare("INSERT INTO articles (title, content) VALUES (:title, :content)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
$stmt->execute();
// 输出时防止XSS
echo htmlspecialchars($article['content'], ENT_QUOTES, 'UTF-8');
分页功能实现
处理大量文章时的分页显示逻辑。

$perPage = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->query("SELECT COUNT(*) FROM articles");
$total = $stmt->fetchColumn();
$pages = ceil($total / $perPage);
$stmt = $pdo->prepare("SELECT * FROM articles ORDER BY created_at DESC LIMIT :offset, :perPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
$articles = $stmt->fetchAll();
以上实现包含了文章管理系统的基本功能模块,可根据实际需求进行扩展和优化。注意在生产环境中要添加更完善的安全措施和错误处理机制。






