当前位置: 首页 > news >正文

关于PHP学习

用PHP写一个简单的博客文章功能,通常需要结合数据库存储文章数据,并通过PHP处理数据的增删改查。以下是一个基础的实现思路和示例代码:

 

一、核心功能设计

 

1. 数据库设计(以MySQL为例):存储文章标题、内容、发布时间等信息

2. 文章列表页:展示所有博客文章的标题和发布时间

3. 文章详情页:显示单篇文章的完整内容

4. 简单的发布功能(可选):添加新文章

 

二、数据库表设计

 

先创建一个 articles 表,用于存储文章数据:

 

CREATE TABLE articles (

  id INT PRIMARY KEY AUTO_INCREMENT,

  title VARCHAR(255) NOT NULL, -- 文章标题

  content TEXT NOT NULL, -- 文章内容

  created_at DATETIME DEFAULT CURRENT_TIMESTAMP -- 发布时间

);

 

 

三、PHP代码实现(示例)

 

1. 数据库连接配置(config.php)

 

<?php

$host = 'localhost'; // 数据库主机

$dbname = 'blog'; // 数据库名

$username = 'root'; // 数据库用户名

$password = ''; // 数据库密码

 

// 连接数据库

try {

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    die("数据库连接失败: " . $e->getMessage());

}

?>

 

 

2. 文章列表页(index.php)

 

<?php include 'config.php'; ?>

<!DOCTYPE html>

<html>

<head>

    <title>我的博客</title>

    <meta charset="utf-8">

</head>

<body>

    <h1>博客文章列表</h1>

    <a href="post.php">发布新文章</a>

    <hr>

 

    <?php

    // 查询所有文章(按发布时间倒序)

    $stmt = $pdo->query("SELECT * FROM articles ORDER BY created_at DESC");

    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);

 

    if (count($articles) > 0) {

        foreach ($articles as $article) {

    ?>

            <div>

                <h2><a href="detail.php?id=<?= $article['id'] ?>"><?= htmlspecialchars($article['title']) ?></a></h2>

                <p>发布时间: <?= $article['created_at'] ?></p>

                <hr>

            </div>

    <?php

        }

    } else {

        echo "<p>暂无文章,快去发布第一篇吧!</p>";

    }

    ?>

</body>

</html>

 

 

3. 文章详情页(detail.php)

 

<?php 

include 'config.php';

// 获取URL中的文章ID

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

 

// 查询单篇文章

$stmt = $pdo->prepare("SELECT * FROM articles WHERE id = :id");

$stmt->bindParam(':id', $id);

$stmt->execute();

$article = $stmt->fetch(PDO::FETCH_ASSOC);

 

if (!$article) {

    die("文章不存在!");

}

?>

<!DOCTYPE html>

<html>

<head>

    <title><?= htmlspecialchars($article['title']) ?></title>

    <meta charset="utf-8">

</head>

<body>

    <a href="index.php">返回列表</a>

    <h1><?= htmlspecialchars($article['title']) ?></h1>

    <p>发布时间: <?= $article['created_at'] ?></p>

    <hr>

    <div><?= nl2br(htmlspecialchars($article['content'])) ?></div> <!-- nl2br转换换行符 -->

</body>

</html>

 

 

4. 发布文章页(post.php)

 

<?php

include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // 获取表单提交的数据

    $title = $_POST['title'] ?? '';

    $content = $_POST['content'] ?? '';

 

    // 简单验证

    if (empty($title) || empty($content)) {

        $error = "标题和内容不能为空!";

    } else {

        // 插入数据库

        $stmt = $pdo->prepare("INSERT INTO articles (title, content) VALUES (:title, :content)");

        $stmt->bindParam(':title', $title);

        $stmt->bindParam(':content', $content);

        $stmt->execute();

 

        // 跳转回列表页

        header('Location: index.php');

        exit;

    }

}

?>

<!DOCTYPE html>

<html>

<head>

    <title>发布文章</title>

    <meta charset="utf-8">

</head>

<body>

    <h1>发布新文章</h1>

    <?php if (isset($error)) echo "<p style='color:red'>$error</p>"; ?>

    <form method="post">

        <div>

            <label>标题:</label><br>

            <input type="text" name="title" style="width: 500px;">

        </div>

        <br>

        <div>

            <label>内容:</label><br>

            <textarea name="content" rows="10" cols="80"></textarea>

        </div>

        <br>

        <button type="submit">发布</button>

        <a href="index.php">取消</a>

    </form>

</body>

</html>

 

 

四、使用说明

 

1. 先在MySQL中创建名为 blog 的数据库(或修改 config.php 中的数据库名)

2. 执行上述SQL语句创建 articles 表

3. 将所有文件放在PHP运行环境(如XAMPP、WAMP)的网站根目录下

4. 访问 index.php 即可查看博客列表,点击“发布新文章”添加内容

 

这个示例实现了最基础的博客功能,实际使用中还可以扩展:添加用户登录、文章编辑/删除、评论功能、富文本编辑器等。

http://www.lryc.cn/news/605677.html

相关文章:

  • 【BUG】nvm无法安装低版本Node.js:The system cannot find the file specified解决方案
  • iOS15及以后国际化如何设置.xcstrings文件默认语言
  • Jmeter全局变量跨线程组的使用
  • ShimetaPi M4-R1:国产高性能嵌入式平台的异构计算架构与OpenHarmony生态实践
  • Video Pixel Repetition
  • Spring AI MCP 技术从使用到项目实战深度解析
  • 数据结构:多项式加法(Polynomial Addition)
  • Linux多线程线程控制
  • PHP开发
  • 《质光相济:Three.js中3D视觉的底层交互逻辑》
  • Redis高频问题全解析
  • 深度理解 linux 系统内存分配
  • [特殊字符] 数字孪生 + 数据可视化:实战经验分享,让物理世界数据 “会说话”
  • Java【代码 21】将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理
  • ubuntu24.04环境下树莓派Pico C/C++ SDK开发环境折腾记录
  • STM32学习记录--Day4
  • 云原生运维与混合云运维:如何选择及 Wisdom SSH 的应用
  • AI编程新工具!使用 LangGraph 构建复杂工作流
  • Cesium 快速入门(七)材质详解
  • 数据结构 ArrayList与顺序表
  • 计算机网络学习(一、Cisco Packet Tracer软件安装)
  • Redis线程模型讨论
  • 无人机飞控系统3D (C++)实践
  • 思途JSP学习 0731
  • Druid数据库连接池
  • MongoDB系列教程-第四章:MongoDB Compass可视化和管理MongoDB数据库
  • 使用 Elasticsearch 和 AI 构建智能重复项检测
  • Jmeter 命令行压测、HTML 报告、Jenkins 配置目录
  • HTML-取消div,a等标签点击效果
  • 深入探索Weaviate:构建高效AI应用的数据库解决方案