本文目录导读:

我来详细介绍如何在PHP中实现新闻系统功能。
数据库设计
首先创建新闻数据表:
CREATE TABLE news (
id INT PRIMARY KEY AUTO_INCREMENT,VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
author VARCHAR(100),
category VARCHAR(50),
status ENUM('draft', 'published') DEFAULT 'draft',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
views INT DEFAULT 0
);
新闻连接类
<?php
// db.php - 数据库连接
class Database {
private $host = "localhost";
private $dbname = "news_db";
private $username = "root";
private $password = "";
public $conn;
public function getConnection() {
try {
$this->conn = new PDO(
"mysql:host=$this->host;dbname=$this->dbname;charset=utf8",
$this->username,
$this->password
);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->conn;
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
return null;
}
}
}
?>
新闻管理类
<?php
// news.php - 新闻操作类
class News {
private $conn;
public function __construct() {
$db = new Database();
$this->conn = $db->getConnection();
}
// 获取所有新闻(分页)
public function getAllNews($page = 1, $limit = 10) {
$offset = ($page - 1) * $limit;
$query = "SELECT * FROM news WHERE status = 'published'
ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// 获取单条新闻
public function getNewsById($id) {
$query = "SELECT * FROM news WHERE id = :id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
// 增加浏览量
$this->incrementViews($id);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// 添加新闻
public function addNews($title, $content, $author, $category) {
$query = "INSERT INTO news (title, content, author, category, status)
VALUES (:title, :content, :author, :category, 'published')";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
$stmt->bindParam(':author', $author);
$stmt->bindParam(':category', $category);
return $stmt->execute();
}
// 更新新闻
public function updateNews($id, $title, $content, $category) {
$query = "UPDATE news SET title = :title, content = :content,
category = :category, updated_at = NOW() WHERE id = :id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
$stmt->bindParam(':category', $category);
return $stmt->execute();
}
// 删除新闻
public function deleteNews($id) {
$query = "DELETE FROM news WHERE id = :id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':id', $id);
return $stmt->execute();
}
// 增加浏览量
private function incrementViews($id) {
$query = "UPDATE news SET views = views + 1 WHERE id = :id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
}
// 获取新闻总数
public function getTotalNews() {
$query = "SELECT COUNT(*) as total FROM news WHERE status = 'published'";
$stmt = $this->conn->query($query);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result['total'];
}
// 搜索新闻
public function searchNews($keyword) {
$query = "SELECT * FROM news WHERE title LIKE :keyword
OR content LIKE :keyword AND status = 'published'";
$stmt = $this->conn->prepare($query);
$searchTerm = "%" . $keyword . "%";
$stmt->bindParam(':keyword', $searchTerm);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
前台显示页面
<?php
// news_list.php - 新闻列表页
require_once 'news.php';
$news = new News();
// 获取分页参数
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$perPage = 10;
$totalNews = $news->getTotalNews();
$totalPages = ceil($totalNews / $perPage);
$newsList = $news->getAllNews($page, $perPage);
?>
<!DOCTYPE html>
<html>
<head>新闻列表</title>
<style>
.news-item {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
}
.news-item h2 {
margin: 0 0 10px 0;
}
.news-meta {
color: #666;
font-size: 14px;
margin-bottom: 10px;
}
.pagination {
margin-top: 20px;
}
.pagination a {
padding: 8px 12px;
margin: 0 5px;
text-decoration: none;
border: 1px solid #ddd;
}
.pagination .current {
background: #007bff;
color: white;
}
</style>
</head>
<body>
<h1>最新新闻</h1>
<!-- 搜索表单 -->
<form method="GET" action="search.php" style="margin-bottom: 20px">
<input type="text" name="keyword" placeholder="搜索新闻...">
<input type="submit" value="搜索">
</form>
<?php foreach ($newsList as $item): ?>
<div class="news-item">
<h2>
<a href="news_detail.php?id=<?php echo $item['id']; ?>">
<?php echo htmlspecialchars($item['title']); ?>
</a>
</h2>
<div class="news-meta">
<span>作者: <?php echo htmlspecialchars($item['author']); ?></span> |
<span>分类: <?php echo $item['category']; ?></span> |
<span>时间: <?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?></span> |
<span>浏览: <?php echo $item['views']; ?></span>
</div>
<p><?php echo mb_substr(strip_tags($item['content']), 0, 200, 'utf-8') . '...'; ?></p>
<a href="news_detail.php?id=<?php echo $item['id']; ?>">阅读更多</a>
</div>
<?php endforeach; ?>
<!-- 分页 -->
<div class="pagination">
<?php for($i = 1; $i <= $totalPages; $i++): ?>
<?php if($i == $page): ?>
<span class="current"><?php echo $i; ?></span>
<?php else: ?>
<a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php endif; ?>
<?php endfor; ?>
</div>
</body>
</html>
新闻详情页
<?php
// news_detail.php - 新闻详情页
require_once 'news.php';
$id = isset($_GET['id']) ? $_GET['id'] : 0;
$news = new News();
$item = $news->getNewsById($id);
if (!$item) {
die('新闻不存在');
}
?>
<!DOCTYPE html>
<html>
<head><?php echo htmlspecialchars($item['title']); ?></title>
</head>
<body>
<h1><?php echo htmlspecialchars($item['title']); ?></h1>
<div style="color: #666; margin: 10px 0">
作者: <?php echo htmlspecialchars($item['author']); ?> |
时间: <?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?> |
浏览: <?php echo $item['views']; ?>次
</div>
<div style="line-height: 1.8">
<?php echo nl2br($item['content']); ?>
</div>
<a href="news_list.php">返回列表</a>
</body>
</html>
管理后台
<?php
// admin/news_crud.php - 新闻添加/编辑
require_once '../news.php';
$news = new News();
$action = isset($_GET['action']) ? $_GET['action'] : 'add';
$id = isset($_GET['id']) ? $_GET['id'] : 0;
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_POST['author'];
$category = $_POST['category'];
if ($action == 'edit') {
$news->updateNews($id, $title, $content, $category);
} else {
$news->addNews($title, $content, $author, $category);
}
header('Location: news_admin.php');
exit;
}
// 编辑时获取原数据
$item = null;
if ($action == 'edit' && $id > 0) {
$item = $news->getNewsById($id);
}
?>
<!DOCTYPE html>
<html>
<head>新闻管理</title>
</head>
<body>
<h2><?php echo $action == 'edit' ? '编辑新闻' : '添加新闻'; ?></h2>
<form method="POST">
<p>
<label>标题:</label>
<input type="text" name="title" required
value="<?php echo $item ? htmlspecialchars($item['title']) : ''; ?>"
style="width: 100%">
</p>
<p>
<label>内容:</label>
<textarea name="content" rows="10" required
style="width: 100%"><?php echo $item ? htmlspecialchars($item['content']) : ''; ?></textarea>
</p>
<p>
<label>作者:</label>
<input type="text" name="author" required
value="<?php echo $item ? htmlspecialchars($item['author']) : 'admin'; ?>">
</p>
<p>
<label>分类:</label>
<select name="category">
<option value="news" <?php echo $item && $item['category'] == 'news' ? 'selected' : ''; ?>>新闻</option>
<option value="tech" <?php echo $item && $item['category'] == 'tech' ? 'selected' : ''; ?>>科技</option>
<option value="sports" <?php echo $item && $item['category'] == 'sports' ? 'selected' : ''; ?>>体育</option>
</select>
</p>
<input type="submit" value="保存">
</form>
</body>
</html>
核心功能说明
安全优化建议:
// 添加安全性检查
class Security {
public static function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
public static function csrf_token() {
return $_SESSION['csrf_token'] ?? $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
}
性能优化:
// 添加缓存机制
function getNewsWithCache($id) {
$cacheKey = "news_" . $id;
// 检查缓存
if ($cached = apcu_fetch($cacheKey)) {
return $cached;
}
// 从数据库获取
$news = new News();
$data = $news->getNewsById($id);
// 存入缓存,过期时间 5 分钟
apcu_store($cacheKey, $data, 300);
return $data;
}
这是一个完整的PHP新闻系统基础架构,你可以根据需要添加更多功能,如:多图片上传、评论系统、RSS订阅等,记得在实际部署时添加用户认证和权限管理。