Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Comment Code Help

I'm in the process of coding my very first blog. With the help of various tutorials, and other forums I have managed to gather a semi-working code.

Right now I have a code that takes and displays the comment, but the problem is coordinating which comments go on which post. My current set up is all my post are HTML files, and the comments are stored in a database. I also have a form that creates a new row with a unique post ID and title for each post.

My basic DB setup right now is as follows: 1 database, 2 tables. A post table and a comments table. In the comments table I have the general name, website, comment, etc. and I also have a unique ID that auto-increments for each comment. Then I have a post_id which should match up with the designated post.

On the post table, I have just two fields: entry_id and title. The title is manually set by me and the entry_id is auto-incremented. NOTE: The entry itself is NOT stored in the database.

So my current problem is how to set the post_id for each page of comments and how to associate the entry_id with the actual post. I hope that's not too confusing. Thanks a ton for any help!

-iMaster

like image 791
williamg Avatar asked Feb 28 '23 00:02

williamg


2 Answers

I think that you should consider refactoring your code to store the post in your database.

From there, you'd have a page (http://mysite/showpost.php?post_id=5) that displays your post (psuedo-code'ish):

<?php

// establish database connection here

// Simple SQL injection prevention:
foreach ($_REQUEST as $key => $value)
{
  $_REQUEST[$key] = mysql_real_escape_string($value);
}

// Get the appropriate post from the posts table.
$query = "SELECT post FROM posts WHERE post_id={$_REQUEST['post_id']}";
$result = mysql_query($query);
$row = mysql_fetch_assoc($query);

echo $row['posts'];

// Get the appropriate comments from the comments table.
$query = "SELECT comment FROM comments WHERE post_id={$_REQUEST['post_id']}";
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result))
{
  echo "Comment: {$row['comment']}";
}

// close connections, etc.    

?>

My PHP is very rusty, but this should give you a good idea of the data structure and code needed to accomplish what you want.

like image 188
Ian P Avatar answered Mar 05 '23 17:03

Ian P


Good for you for learning to "roll your own" and get exactly what you want and learn something along the way.

You should create a table for comments with a foreign key that matches the article ID.

Then when displaying your comments, do a query to fetch all comments associated with that article ID.

like image 44
Jeremy Morgan Avatar answered Mar 05 '23 18:03

Jeremy Morgan