0
点赞
收藏
分享

微信扫一扫

11. 博客系统CMS

悬灸人雪洋 2024-11-18 阅读 15

代码:

// db.php - 数据库连接
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "blog_system_cms";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// add_post.php - 创建博客文章
if(isset($_POST['add_post'])){
    $title = $_POST['title'];
    $content = $_POST['content'];
    $category = $_POST['category'];
    $author = $_POST['author'];
    
    $sql = "INSERT INTO posts (title, content, category, author) VALUES ('$title', '$content', '$category', '$author')";
    if(mysqli_query($conn, $sql)){
        echo "Post created successfully!";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}

// show_posts.php - 显示所有博客文章
$query = "SELECT * FROM posts ORDER BY created_at DESC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
    echo "<h2>" . $row['title'] . "</h2>";
    echo "<p>" . $row['content'] . "</p>";
    echo "<p>Category: " . $row['category'] . "</p>";
    echo "<p>Author: " . $row['author'] . "</p>";
}

// add_comment.php - 添加评论
if(isset($_POST['add_comment'])){
    $post_id = $_POST['post_id'];
    $comment = $_POST['comment'];
    
    $sql = "INSERT INTO comments (post_id, comment) VALUES ('$post_id', '$comment')";
    if(mysqli_query($conn, $sql)){
        echo "Comment added!";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}

// show_comments.php - 显示评论
$post_id = $_GET['post_id'];
$query = "SELECT * FROM comments WHERE post_id = '$post_id'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
    echo "<p>" . $row['comment'] . "</p>";
}

举报

相关推荐

0 条评论