You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

博客无法发布求助:分类可写入数据库但帖子提交失败

Troubleshooting Your Blog Post Submission Issue

Hey there, let's break down why your posts aren't saving to the database while categories work fine. Since categories are writing successfully, we know your database connection is functional—so the issue is likely in your post-specific validation, insertion logic, or a small oversight in your code.

First, Let's Fix & Audit Your Truncated Code

Your code snippet cuts off at the contents validation step, so let's fill that gap and add debug tools to catch hidden issues:

<?php 
include_once('header.php'); 
// Enable full error reporting to catch hidden PHP issues
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(isset($_POST['title'], $_POST['contents'], $_POST['category'])){ 
    $errors = array(); 

    // Validate title
    if(!empty(trim($_POST['title']))){ 
        $title = trim($_POST['title']); 
    }else{ 
        $errors[] = 'Please enter title'; 
    } 

    // Validate contents (your code was truncated here)
    if(!empty(trim($_POST['contents']))){ 
        $contents = trim($_POST['contents']); 
    }else{ 
        $errors[] = 'Please enter post content'; 
    } 

    // Validate category (critical: ensure it maps to a valid DB entry)
    $selected_category = trim($_POST['category']);
    // If your categories table uses IDs (common for foreign keys), fetch the ID first
    $cat_check_query = "SELECT id FROM categories WHERE name = ?";
    $stmt = $conn->prepare($cat_check_query);
    $stmt->bind_param("s", $selected_category);
    $stmt->execute();
    $cat_result = $stmt->get_result();

    if($cat_result->num_rows === 0){
        $errors[] = 'Selected category does not exist';
    }else{
        $category_id = $cat_result->fetch_assoc()['id'];
    }

    // If no errors, attempt to insert the post
    if(empty($errors)){
        // Adjust the SQL to match your posts table's actual column names
        $insert_post_query = "INSERT INTO posts (title, contents, category_id) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($insert_post_query);
        // Bind parameters: "ssi" = string, string, integer (match your column types!)
        $stmt->bind_param("ssi", $title, $contents, $category_id);

        if($stmt->execute()){
            echo "Post submitted successfully!";
        }else{
            // Print the exact database error to diagnose insertion failures
            echo "Database error: " . $conn->error;
        }
    }else{
        // Show validation errors to the user
        foreach($errors as $error){
            echo "<p style='color: red;'>* $error</p>";
        }
    }
}
?>

Key Troubleshooting Steps to Check

  • Validate Your Form Fields:
    Double-check that your HTML form's name attributes match exactly what you're using in $_POST (e.g., if your form has name="content" instead of name="contents", PHP won't pick it up). Ensure you're trimming and validating all required fields—missing validation could leave variables empty, causing INSERT failures.

  • Check Database Insert Logic:
    Verify your posts table schema: Are the column names (like title, contents, category_id) correct? Did you forget to add a required column (like created_at with a default value)? If you're using foreign keys for categories, make sure you're inserting the category ID (not the name) into the posts table—mismatched data types will trigger a database error.

  • Enable Debugging:
    Keep the error reporting lines at the top of your script to catch PHP warnings/notices you might be missing. After attempting an INSERT, print the database error message (like $conn->error for mysqli) to see exactly why the query failed—this is the fastest way to spot issues like duplicate keys, missing columns, or permission problems.

  • Check Variable Scope:
    Confirm your database connection object (e.g., $conn) is available in this script—if header.php initializes the connection but closes it before this code runs, your INSERT will fail silently.

内容的提问来源于stack exchange,提问作者broda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:53:22