php实现文章
PHP实现文章管理功能
在PHP中实现文章管理功能通常涉及数据库操作、表单处理和页面展示。以下是实现文章管理的基本步骤:
数据库设计 创建articles表,包含字段如id、title、content、author、created_at等。SQL示例:
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
);
数据库连接 使用PDO或mysqli连接数据库:

$dsn = 'mysql:host=localhost;dbname=your_db;charset=utf8';
$user = 'username';
$pass = 'password';
try {
$pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
文章发布功能 创建表单页面和处理脚本:
<form action="publish.php" method="post">
<input type="text" name="title" placeholder="标题">
<textarea name="content" placeholder="内容"></textarea>
<input type="submit" value="发布">
</form>
// publish.php
$title = $_POST['title'];
$content = $_POST['content'];
$stmt = $pdo->prepare("INSERT INTO articles (title, content) VALUES (?, ?)");
$stmt->execute([$title, $content]);
header('Location: index.php');
文章列表展示 查询并显示文章列表:

$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['created_at']}</small>";
}
文章编辑和删除 实现编辑和删除功能:
// 编辑
$stmt = $pdo->prepare("UPDATE articles SET title=?, content=? WHERE id=?");
$stmt->execute([$newTitle, $newContent, $id]);
// 删除
$stmt = $pdo->prepare("DELETE FROM articles WHERE id=?");
$stmt->execute([$id]);
安全考虑 对用户输入进行验证和过滤:
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
$content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
分页功能 实现文章列表分页:
$perPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare("SELECT * FROM articles ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$perPage, $offset]);
以上代码示例展示了PHP实现文章管理的基本功能。实际应用中可能需要添加用户认证、富文本编辑器、图片上传等功能。






