I created a page that displays each of the posts from a posts table in my database. You can add a new post to the database from this page and the post displays at the top. This functions just fine.
Within each post, is a comment form that inserts comments to a comments table in the database. This works fine for the top most post. It adds the correct post_id from the post the comment is attached to and the user_id from the session.
The problem is that when you add a comment from one of the posts below the first one, the blank data from the first posts comment is what is saved to the data base and is attached only to the first post.
I know that I somehow need to attach the active posts post_id to the submit button or somehow find another way to separate the posts but barely understood enough to get as far as I did.
I need to know the best approach to fix this concept rather than having to make each comment be on it's own post page, if this makes sense.
I am sure that this has something to do with the id's being the same and not knowing which post they belong to but I don't know what I am missing something that would make each comment insert the correct posts data.
This is the full code all on one page except for the insertContact.php file that i will add below this. I appreciate all advice on what I am missing and ideas of how I should have done this better.
<?php require_once('../Connections/gm.php'); ?>
<?php require_once('../webassist/mysqli/authentication.php'); ?>
<?php require_once('../webassist/mysqli/rsobj.php'); ?>
<?php require_once('../webassist/mysqli/queryobj.php'); ?>
<?php
if (true) {
$RestrictAccess = new WA_MySQLi_Auth();
$RestrictAccess->Action = "restrict";
$RestrictAccess->Name = "authenticate";
$RestricAccessRedirect = "../login.php";
if (function_exists("rel2abs")) $RestricAccessRedirect = $RestricAccessRedirect?rel2abs($RestricAccessRedirect,dirname(__FILE__)):"";
$RestrictAccess->FailRedirect = $RestricAccessRedirect;
$RestrictAccess->execute();
}
?>
<?php
if (isset($_POST["Insert"]) || isset($_POST["Insert_x"])) {
$InsertQuery = new WA_MySQLi_Query($gm);
$InsertQuery->Action = "insert";
$InsertQuery->Table = "posts";
$InsertQuery->bindColumn("user_id", "i", "".$_SESSION['UserID'] ."", "WA_DEFAULT");
$InsertQuery->bindColumn("content", "s", "".((isset($_POST["content"]))?$_POST["content"]:"") ."", "WA_DEFAULT");
$InsertQuery->saveInSession("WADA_Insert_posts");
$InsertQuery->execute();
$InsertGoTo = "";
if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
$InsertQuery->redirect($InsertGoTo);
}
?>
<?php
$rsUser = new WA_MySQLi_RS("rsUser",$gm,1);
$rsUser->setQuery("SELECT * FROM users WHERE UserID = ?");
$rsUser->bindParam("i", "".($_SESSION['UserID']) ."", "-1"); //colname
$rsUser->execute();
?>
<?php
$rsPosts = new WA_MySQLi_RS("rsPosts",$gm,0);
$rsPosts->setQuery("SELECT posts.id, posts.content, posts.date_created, UserFirstName, UserLastName FROM posts JOIN users ON users.UserID = posts.user_id ORDER BY date_created DESC");
$rsPosts->execute();?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../css/bootstrap-4.4.1.css" rel="stylesheet">
<link href="../css/tabsStyle.css" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://kit.fontawesome.com/73a59d5041.js" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?php require("../members/nav.php"); ?>
<!--Add New Post Modal-->
<div class="offcanvas offcanvas-top" id="post">
<div class="offcanvas-header">
<h1 class="offcanvas-title">Add New Post</h1>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
</div>
<div class="offcanvas-body">
<form enctype="multipart/form-data" class="Basic_Default" id="Insert_Basic_Default" name="Insert_Basic_Default" method="post" action="">
<fieldset class="Basic_Default" id="Insert">
<input type="hidden" value="<?php echo $_SESSION['UserID']; ?>" name="user_id">
<textarea name="content" id="content" cols="30" rows="2" class="form-control" placeholder="Hello <?php echo($rsPosts->getColumnVal("UserFirstName")); ?>, what's on your mind?"></textarea><br>
<div class="d-block w-100">
<input type="submit" value="Insert" class="btn btn-block btn-primary btn-sm" id="Insert" name="Insert" />
</div>
</fieldset>
</form>
</div>
</div>
<!--Add New Post Modal End-->
<section>
<!--BODY CONTENTS-->
<div class="container bg-light">
<!--Open Add Post Modal Button-->
<div class="row">
<div class="col-7 mb-2 text-left"><br>
<h2>Neighborhood Posts</h2>
</div>
<div class="col-5 mb-2 text-right">
<!--Button-->
<div class="container-fluid mt-3">
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#post">
Add New Post
</button>
</div>
</div>
</div>
<hr>
<!--Open Add Post Modal Button End-->
<div class="row">
<div class="col-12 mb-2 text-center">
<!--MIDDLE OF BOX START-->
<?php
$wa_repeatfor = -1; // Start Repeat Each Post
if (!isset($wa_repeatcount)) $wa_repeatcount = 0;
while (!$rsPosts->atEnd() && $wa_repeatfor != 0) {
$wa_repeatfor--;
$wa_repeatcount++;
if (!$rsPosts->atEnd()) {
?>
<div class="mt-4">
<!--Posts Start-->
<ul class="pt-3 shadow-sm card text-left">
<p style="color: #848383"><span class="small">Posted by </span><?php echo($rsPosts->getColumnVal("UserFirstName")); ?> <?php echo($rsPosts->getColumnVal("UserLastName")); ?><span class="small"> on <?php echo(($rsPosts->getColumnVal("date_created"))?date('n/d/Y h:i:sa',strtotime($rsPosts->getColumnVal("date_created"))):''); ?></span><br>
<span style="color: #000; font-size: 16px"><?php echo($rsPosts->getColumnVal("content")); ?></span></p>
<!--Comment Recordset Start-->
<?php
$rsComment = new WA_MySQLi_RS("rsComment",$gm,0);
$rsComment->setQuery("SELECT posts.id, posts.user_id, posts.content, posts.date_created, comments.`comment`, comments.date_created, users.UserFirstName, users.UserLastName, users.profile_pic FROM posts INNER JOIN comments ON posts.id = comments.post_id INNER JOIN users ON comments.user_id = users.UserID WHERE comments.post_id = ?");
$rsComment->bindParam("i", "".($rsPosts->getColumnVal("id")) ."", "-1"); //WAQB_Param1
$rsComment->execute();
?>
<!--Comment Recordset End-->
<!--Comment Repeat Start-->
<div class="container">
<ul class="m-3 shadow-sm card text-bg-info">
<?php
$wa_startindex = 0;
while(!$rsComment->atEnd()) {
$wa_startindex = $rsComment->Index;
?>
<dd><span class="small">Comment by </span><?php echo($rsComment->getColumnVal("UserFirstName")); ?> <?php echo($rsComment->getColumnVal("UserLastName")); ?><span class="small"> on <?php echo(($rsComment->getColumnVal("date_created"))?date('n/d/Y h:i:sa',strtotime($rsComment->getColumnVal("date_created"))):''); ?> - </span><?php echo($rsComment->getColumnVal("comment")); ?></dd>
<?php
$rsComment->moveNext();
}
$rsComment->moveFirst(); //return RS to first record
unset($wa_startindex);
unset($wa_repeatcount);
?>
</ul>
</div>
<!--Comment Repeat End-->
<!--ADD A COMMENT-->
<div class="d-flex justify-content-center">
<!--Comment Form-->
<form action="insertContact.php" id="commentForm" method="post" onSubmit="return formCommentSubmit();">
<input hidden="post_id" name="post_id" id="post_id" value="<?php echo($rsPosts->getColumnVal("id")); ?>">
<input hidden="user_id" name="user_id" id="user_id" value="<?php echo $_SESSION['UserID']; ?>">
<textarea name="comment" id="comment" cols="30" rows="2" class="form-control" placeholder="Would you like to comment?"></textarea>
<div class="mb-3">
</div>
<div class="d-grid">
<button type="submit" name="commentForm" class="btn btn-primary btn-sm">Add Comment</button>
</div>
<br>
</form>
<script type="text/javascript">
function formCommentSubmit() {
$.ajax({
type: 'POST',
async: false,
url: 'insertContact.php',
dataType: "JSON",
data: $('#commentForm').serialize(),
});
var form = document.getElementById('commentForm').reset();
return false;
}
</script>
<!--Comment Form End-->
</div>
<!--ADD A COMMENT END-->
</ul>
<!--Posts End-->
</div>
<?php
if ($wa_repeatfor != 0) $rsPosts->moveNext(); // Repeat Alternate
} else {
?>
<?php
} // End Repeat Alternate
?>
<?php
}
if (!isset($wa_startindex)) $rsPosts->moveFirst(); // End Repeat Each Post
?>
<!--MIDDLE OF BOX END-->
</div>
</div>
</div>
<!--BODY CONTENTS END-->
<script src="../js/jquery-3.4.1.min.js"></script>
<script src="../js/popper.min.js"></script>
<script src="../js/bootstrap-4.4.1.js"></script>
</body>
</html>
Here is the insertContact.php file code: (i removed the DB connection info)
<?php
$connect=mysqli_connect("localhost","","","");
if($_POST) {
$post_id = $_POST['post_id'];
$user_id = $_POST['user_id'];
$comment = $_POST['comment'];
$sql = "INSERT INTO comments(post_id, user_id, comment) VALUES('$post_id', '$user_id', '$comment')";
} else echo 0;
?>
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
JQuery is arguably the most popular JavaScript library with so many features for modern development. JQuery is a fast and concise JavaScript library created by John Resig in 2006. It is a cross-platform JavaScript library designed to simplify client-side HTML scripting. Over 19 million websites are currently using jQuery! Companies like WordPress, Facebook, Google, IBM and many more rely on jQuery to provide a kind of web browsing experience.
https://jquery.com/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
CSS (Cascading Style Sheets) is a formal language for describing the appearance of a document written using a markup language.
It is mainly used as a means of describing, decorating the appearance of web pages written using HTML and XHTML markup languages, but can also be applied to any XML documents, such as SVG or XUL.
https://www.w3.org/TR/CSS/#css
Bootstrap is not exclusively a CSS framework, but its most popular features are CSS-centric. These include a powerful grid, icons, buttons, map components, navigation bars, and more.
https://getbootstrap.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.