I am relatively new to PHP and SQL and I am creating a simple blog tool for my own page and I'm stuck on how I can make a comment section. I have 2 tables general, which contains the blog post and additional information comments, which contains comments
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM general WHERE hidden = 'false' ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
echo "<div class='blogpost'>
<div class='blogbody'></div>";
//I need to do a query into the comments table at this point to find
//all comments matching the criteria to be matched with the post here.
echo "<div class='comments'></div></div>";
}
}
else{
echo "no posts";
}
I manage to get the blogposts working but as soon as I try a second query by adding
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error){
die ("connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT * FROM comments WHERE $row["parent"] ORDER BY id DESC";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0){
while ($row2 = $result2->fetch_assoc()){
}
}
else{
echo "no comments";
}
it all just breaks. I am not able to throw in a loop that gets all the comments for the specific post before it starts loading additional posts.
How would I go on about solving this? I might need a little spoonfeeding with comments in any code samples,
You can use the primary key of the post and that can be used in comments table as a foreign key so that you can easily make your query with that will show all the comments against that specific post. Then the query will be like this:
$postid=$row['post_id'];
$sql2 = "SELECT * FROM comments WHERE post_id='$postid' ORDER BY post_id DESC";
Changing the second query to fixed the problem.
WHERE $row["parent"] ORDER. Change that to WHERE parent={$row['parent']} ORDER
Thanks to Jeff for providing this answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.