首页 >后端开发 >php教程 >PHP 速成课程:简单的博客平台

PHP 速成课程:简单的博客平台

WBOY
WBOY原创
2024-08-05 14:54:20815浏览

PHP crash course: Simple Blog Platform

一个基本的博客平台,用户可以在其中发布、编辑和删除文章。使用 PHP、HTML、jQuery、AJAX、JSON、Bootstrap、CSS 和 MySQL 构建。

主题:php、mysql、博客、ajax、bootstrap、jquery、css

分步解决方案

1. 目录结构

simple-blog-platform/
│
├── config.sample.php
├── index.html
├── db/
│   └── database.sql
├── src/
│   ├── get-post.php
│   └── post-handler.php
├── include/
│   ├── config.sample.php
│   └── db.php
├── assets/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── script.js
│   └── images/
├── README.md
└── .gitignore

2. 数据库架构

db/database.sql:

CREATE DATABASE IF NOT EXISTS blog_db;
USE blog_db;

CREATE TABLE IF NOT EXISTS posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. 配置文件

include/config.sample.php:

<?php
define('DB_HOST', 'localhost'); // Database host
define('DB_NAME', 'blog_db'); // Database name
define('DB_USER', 'root'); // Change if necessary
define('DB_PASS', ''); // Change if necessary
?>

4. 配置数据库连接

include/db.php:

<?php
include 'config.php';

// Database configuration
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

// Create a new PDO instance
try {
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error mode to exception
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage(); // Display error message if connection fails
}
?>

5. HTML 和 PHP 结构

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Blog</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="mt-5">Simple Blog</h1>
        <div id="posts"></div>
        <button class="btn btn-primary mt-3" data-toggle="modal" data-target="#postModal">Add Post</button>
    </div>

    <!-- Modal for adding/editing posts -->
    <div class="modal fade" id="postModal" tabindex="-1" role="dialog" aria-labelledby="postModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="postModalLabel">Add Post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="postForm">
                        <input type="hidden" id="postId">
                        <div class="form-group">
                            <label for="title">Title</label>
                            <input type="text" class="form-control" id="title" required>
                        </div>
                        <div class="form-group">
                            <label for="content">Content</label>
                            <textarea class="form-control" id="content" rows="3" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Post</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/script.js"></script>
</body>
</html>

6. JavaScript 和 AJAX

assets/js/script.js

$(document).ready(function() {
    // Load posts when the page loads
    loadPosts();

    // Handle form submission
    $('#postForm').submit(function(event) {
        event.preventDefault(); // Prevent default form submission

        var postId = $('#postId').val();
        var title = $('#title').val();
        var content = $('#content').val();

        $.ajax({
            url: 'src/post-handler.php',
            type: 'POST',
            dataType: 'json',
            data: {
                id: postId,
                title: title,
                content: content
            },
            success: function(response) {
                if (response.success) {
                    $('#postModal').modal('hide');
                    loadPosts(); // Reload posts after saving
                } else {
                    alert('Error: ' + response.message);
                }
            }
        });
    });

    // Load posts function
    function loadPosts() {
        $.ajax({
            url: 'src/get-posts.php',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                var postsHtml = '';
                $.each(data.posts, function(index, post) {
                    postsHtml += '<div class="post"><h2>' + post.title + '</h2><p>' + post.content + '</p></div>';
                });
                $('#posts').html(postsHtml);
            }
        });
    }
});

7. 后端 PHP 脚本

src/get-posts.php

<?php
include '../include/db.php';

header('Content-Type: application/json');

try {
    $stmt = $pdo->query('SELECT * FROM posts ORDER BY created_at DESC');
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['posts' => $posts]);
} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>

src/post-handler.php

<?php
include '../include/db.php';

header('Content-Type: application/json');

// Retrieve POST data
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$title = $_POST['title'];
$content = $_POST['content'];

try {
    if ($id > 0) {
        // Update existing post
        $stmt = $pdo->prepare('UPDATE posts SET title = ?, content = ? WHERE id = ?');
        $stmt->execute([$title, $content, $id]);
    } else {
        // Insert new post
        $stmt = $pdo->prepare('INSERT INTO posts (title, content) VALUES (?, ?)');
        $stmt->execute([$title, $content]);
    }
    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

6.CSS样式

assets/css/style.css

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}

.container {
    margin-top: 20px;
}

.post {
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 15px;
    background-color: #f9f9f9;
}

文档和评论

  • config.php:包含数据库配置并使用PDO连接到MySQL。
  • index.php:具有 HTML 结构的主页,包括用于样式设置的 Bootstrap 以及用于添加/编辑帖子的模式。
  • assets/js/script.js: 处理加载和保存帖子的 AJAX 请求。使用 jQuery 进行 DOM 操作和 AJAX。
  • get-posts.php: 从数据库中获取帖子并将其作为 JSON 返回。
  • post-handler.php: 根据 ID 的存在处理帖子创建和更新。

此设置提供了一个基本的博客平台,用户可以在其中添加和编辑帖子。您可以通过添加用户身份验证、帖子类别、评论等来扩展此功能。

连接链接

如果您发现本系列有帮助,请考虑在 GitHub 上给 存储库 一个星号或在您最喜欢的社交网络上分享该帖子?。您的支持对我来说意义重大!

如果您想要更多类似的有用内容,请随时关注我:

  • 领英
  • GitHub

源代码

以上是PHP 速成课程:简单的博客平台的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn