Unable to Save Post in Forum Application: PHP, MySQL, and JavaScript Issue

Problem: I am working on a simple forum application where users can submit posts via a form. When I click the “Post” button, the post should be saved to a MySQL database, but it doesn’t seem to work. I am getting the error message:

“There was an error in publishing your post.”

I have tried debugging the issue, but I am still unable to figure out what is going wrong. Can someone help me identify the problem and suggest a fix?

What I have tried:

  1. Checked the Frontend JavaScript: I have verified that the form data is being sent to the save_post.php file correctly, but it seems like the data is not being inserted into the database.
  2. Checked the Backend PHP: The save_post.php file seems to be receiving the request, but I am not sure whether the SQL query is executed correctly or not.
  3. Checked the Database: The posts table exists, and I have verified that the structure of the table matches the data I am trying to insert.

Full Code:

HTML and JavaScript (Frontend)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Persistent Komarovi Forum</title>
  <style>
    /* Add your CSS here for styling */
  </style>
</head>
<body>
  <div class="app-container">
    <header>
      <h1>Komarovi Forum</h1>
      <p>Share your thoughts anonymously, upvote posts, and join the discussion!</p>
    </header>
    <main>
      <div class="post-form-container">
        <h2>Create a Post</h2>
        <textarea id="postInput" placeholder="Type your post here..." rows="3"></textarea>
        <button id="submitPost">Post</button>
      </div>
      <section id="posts" class="posts-container">
        <!-- Dynamic posts will be appended here -->
      </section>
    </main>
    <footer>
      <p>Footer content with Instagram logo</p>
    </footer>
  </div>
  <script>
    const postInput = document.getElementById("postInput");
    const submitPost = document.getElementById("submitPost");
    const postsContainer = document.getElementById("posts");

    submitPost.addEventListener("click", () => {
      const content = postInput.value.trim();
      if (content) {
        fetch("save_post.php", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          body: new URLSearchParams({ content: content })
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            loadPosts(); // Reload posts after posting
            postInput.value = ""; // Clear input field
          } else {
            alert("There was an error in publishing your post. Please try again.");
          }
        })
        .catch(() => {
          alert("There was an issue submitting your post. Please try again.");
        });
      }
    });

    function loadPosts() {
      fetch("get_posts.php")
        .then(response => response.json())
        .then(posts => {
          postsContainer.innerHTML = ''; // Clear previous posts
          posts.forEach(post => {
            const postElement = document.createElement("div");
            postElement.innerHTML = `
              <div class="post-content">
                <p>${post.content}</p>
              </div>
            `;
            postsContainer.appendChild(postElement);
          });
        })
        .catch(error => console.error("Error loading posts:", error));
    }

    window.addEventListener("DOMContentLoaded", loadPosts);
  </script>
</body>
</html>

PHP - save_post.php (Backend)

<?php
// Enable error reporting to debug issues
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Database connection (Replace with your actual credentials)
$host = 'localhost';  // Database server
$user = 'root';       // Database username
$password = '';       // Database password
$dbname = 'komarovi_forum'; // Your database name

// Create a connection
$conn = new mysqli($host, $user, $password, $dbname);

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

// Get the post content from the POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = $_POST['content'];

    if (!empty($content)) {
        // SQL query to insert the post into the database
        $stmt = $conn->prepare("INSERT INTO posts (content) VALUES (?)");
        $stmt->bind_param("s", $content); // "s" denotes a string parameter
        
        if ($stmt->execute()) {
            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "error" => "Error inserting the post"]);
        }

        $stmt->close();
    } else {
        echo json_encode(["success" => false, "error" => "Content is empty"]);
    }
}

// Close the database connection
$conn->close();
?>

Database - posts Table Creation (MySQL)

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

Error Message:

When trying to post, the error message displayed is:

“There was an error in publishing your post.”

Expected Outcome:

  • When the user clicks “Post”, the content should be inserted into the MySQL database.
  • The post should then appear in the posts section on the webpage.

What I have already tried:

  • Checked the JavaScript: The request is sent to the save_post.php file, but the post does not get saved.
  • Checked the Database: The database table posts exists, and its structure is correct.
  • Checked the PHP: Error reporting is turned on in PHP to help debug any issues.

What I need help with:

  • Why the data isn’t being inserted into the database?
  • Is the SQL query correct?
  • Is the issue on the PHP backend or frontend?

Database Credentials:

Make sure the database credentials in the save_post.php file are correct and match the ones you use to connect to your MySQL database.

Thanks in advance for your help!

1. Verify Database Connection

Ensure that the database credentials (host, user, password, dbname) in save_post.php are correct and match your MySQL setup. Run a standalone PHP script to confirm the connection:

php

Copy code

<?php
$host = 'localhost';
$user = 'root';
$password = '';
$dbname = 'komarovi_forum';

$conn = new mysqli($host, $user, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Database connected successfully!";
$conn->close();
?>

If the connection fails, update the credentials to match your MySQL setup.


2. Debugging the SQL Query

Enable additional logging and error handling in save_post.php. Modify the error output to include the SQL error message:

php

Copy code

if ($stmt->execute()) {
    echo json_encode(["success" => true]);
} else {
    echo json_encode(["success" => false, "error" => $stmt->error]);
}

This will help identify whether the SQL query is the issue (e.g., syntax error, invalid table name, etc.).


3. Validate POST Data

Ensure that the content field is properly received in save_post.php. Add debugging output to check what the server receives:

php

Copy code

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = $_POST['content'] ?? null;

    if ($content === null) {
        echo json_encode(["success" => false, "error" => "Content is missing in POST request"]);
        exit;
    }
    
    if (!empty($content)) {
        // SQL query to insert the post into the database
        $stmt = $conn->prepare("INSERT INTO posts (content) VALUES (?)");
        $stmt->bind_param("s", $content);
        
        if ($stmt->execute()) {
            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "error" => $stmt->error]);
        }

        $stmt->close();
    } else {
        echo json_encode(["success" => false, "error" => "Content is empty"]);
    }
}

4. Check Content-Type in Frontend

Ensure the POST request’s content type matches what save_post.php expects. You are using application/x-www-form-urlencoded in JavaScript, so the PHP $_POST variable should work.

If there’s an issue, try using application/json instead:

Update Frontend JavaScript:

javascript

Copy code

fetch("save_post.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ content: content }),
})

Update Backend PHP:

php

Copy code

$data = json_decode(file_get_contents("php://input"), true);
$content = $data['content'] ?? null;

5. Ensure Table Exists

Double-check that the posts table exists and matches your SQL structure:

sql

Copy code

SHOW TABLES LIKE 'posts';
DESCRIBE posts;

Ensure the content column is of type TEXT and not null.


6. Enable PHP Logging

If the issue persists, enable logging to view errors in your PHP error log:

  1. Update php.ini:

ini

Copy code

display_errors = On
log_errors = On
error_log = /path/to/php-error.log
  1. Restart your server (e.g., Apache or Nginx).
  2. Check the log file for errors after reproducing the issue.

7. Test Insert Query Manually

Run a manual SQL query in your MySQL terminal or a tool like phpMyAdmin to ensure the query works:

sql

Copy code

INSERT INTO posts (content) VALUES ('Test content');

If this works, the issue is in your PHP code.


Common Pitfalls to Check

  1. Database permissions: Ensure the MySQL user (root) has INSERT privileges on the komarovi_forum.posts table.
  2. Character limits: Check if content exceeds the TEXT field’s limit (65,535 bytes).
  3. CSRF tokens: If your application uses CSRF protection, ensure the token is passed correctly.

Expected Fix

After implementing the debugging steps and updating the code to handle potential issues, the root cause should become apparent. Most likely, the problem lies in:

  • Incorrect database credentials.
  • Issues with receiving the content value in save_post.php.
  • Errors in the SQL query execution.

If these steps don’t resolve the issue, share the updated error messages or outputs for further assistance.