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:
- 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.
- 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.
- 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!