博客无法发布求助:分类可写入数据库但帖子提交失败
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'snameattributes match exactly what you're using in$_POST(e.g., if your form hasname="content"instead ofname="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 yourpoststable schema: Are the column names (liketitle,contents,category_id) correct? Did you forget to add a required column (likecreated_atwith 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->errorfor 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—ifheader.phpinitializes the connection but closes it before this code runs, your INSERT will fail silently.
内容的提问来源于stack exchange,提问作者broda

