php实现新闻
PHP实现新闻系统的核心步骤
数据库设计 创建新闻表(news)包含字段:id(主键)、title(标题)、content(内容)、author(作者)、publish_time(发布时间)、category_id(分类ID)。分类表(categories)存储新闻分类信息。
连接数据库 使用PDO或mysqli扩展连接MySQL数据库,建议采用预处理语句防止SQL注入:
$db = new PDO('mysql:host=localhost;dbname=news_db', 'username', 'password');
新闻发布功能 创建表单提交新闻数据,服务器端接收并存入数据库:
$stmt = $db->prepare("INSERT INTO news(title, content, author) VALUES(?, ?, ?)");
$stmt->execute([$_POST['title'], $_POST['content'], $_POST['author']]);
新闻列表展示 从数据库查询新闻并按时间倒序排列:

$stmt = $db->query("SELECT * FROM news ORDER BY publish_time DESC LIMIT 10");
$newsList = $stmt->fetchAll(PDO::FETCH_ASSOC);
新闻详情页 通过URL参数获取新闻ID并查询详情:
$stmt = $db->prepare("SELECT * FROM news WHERE id = ?");
$stmt->execute([$_GET['id']]);
$news = $stmt->fetch();
新闻分类功能 实现分类查询和展示:
$stmt = $db->prepare("SELECT * FROM news WHERE category_id = ?");
$stmt->execute([$_GET['category_id']]);
进阶功能实现
分页处理 计算总页数和当前页数据:

$perPage = 10;
$total = $db->query("SELECT COUNT(*) FROM news")->fetchColumn();
$pages = ceil($total / $perPage);
$currentPage = min(max(1, $_GET['page'] ?? 1), $pages);
$offset = ($currentPage - 1) * $perPage;
图片上传 处理新闻封面图上传:
if(isset($_FILES['image'])){
$targetDir = "uploads/";
$fileName = basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"], $targetDir.$fileName);
}
搜索功能 实现标题和内容关键词搜索:
$keyword = '%'.$_GET['q'].'%';
$stmt = $db->prepare("SELECT * FROM news WHERE title LIKE ? OR content LIKE ?");
$stmt->execute([$keyword, $keyword]);
缓存优化 使用文件缓存减轻数据库压力:
$cacheFile = 'cache/news_list.cache';
if(file_exists($cacheFile) && time()-filemtime($cacheFile) < 3600){
$newsList = unserialize(file_get_contents($cacheFile));
}else{
// 数据库查询代码
file_put_contents($cacheFile, serialize($newsList));
}






