Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.
Its the part of referencing the ID's. Lets say we have two pages: Page A and Page B. Page A's post ID is 1 Page B's post ID is 2. I'm assuming that on the form to take the comments, I will add another hidden field which sets the post_id for those comments on that particular page. How would I go about setting that value? Does that make sense? Maybe I'm missing something.

Right now, I have two tables: comments and entries. On the comments table I have the name, date, website, comment, etc. and then I have a post_ID.

On the entries table, I have entry ID (auto incremented) and title (set via a from like you suggested).

I don't really know how to explain my problem. It boils down to a SELECT statement that displays all comments whose post_id = entry_id. What I'm having trouble with is connecting those two.

The entry_id is set automatically so that's easy. The post_id will be set....how? And how will I associate each entry_id with the actual file?

I know that's a lot of questions, but I'm trying to accurately express the problems I'm having. Forgive me if I'm working backwards, or if I'm just missing something.

I REALLY appreciate your help. You have NO idea where I'd be without you (well you probably do).

Thanks!

-iMaster
 
I probably should have said this in the beginning, but my posts aren't stored in a database, they're flat files. Therefore, each post doesn't have an ID.

XML based flat files?

As to record ID's in general, regardless of how the data is stored physically, they are advantageous to implement. First of all, it's the fastest and easiest way to reference a specific record. Secondly, it's more secure to find such records based on an ID than using a user name especially if the records are referenced by URL arguments or links. As you design more advanced relationships, i.e. one flat file referencing part of another or a table join in a database, you'll learn about using the ID as a primary key to establish the relationship and ensure fast and efficient data retrieval.

If you implement them into flat files, you might name the xml file using the ID, i.e. in your comments folder each file is 1.xml, 2.xml and so on. Indirectly, you're using a "primary key" relational database technique, if you think about it.

If you merge all the comments into one single flat file, you need to quickly access a specific comment. I'd use XML and set one node to be an ID as I use PHP's powerful XML parser functions to traverse through the file and find the node I want.

Get the idea?
 
I don't really know how to explain my problem. It boils down to a SELECT statement that displays all comments whose post_id = entry_id. What I'm having trouble with is connecting those two.

I partially addressed this earlier.
PHP:
$entry = basename(__FILE__); // gets current file name
$query = mysql_query("SELECT * FROM `blog_comments` WHERE entry='$entry'");
To get the post_id,
PHP:
$postID = mysql_query("SELECT id FROM blog_entries WHERE entry = '$entry' LIMIT 1");
$row = mysql_fetch_assoc($postID);
$post_ID = $row['id'];
// Get all comments relating to this post id
$query = mysql_query("SELECT * FROM `blog_comments` WHERE id='$post_ID'");
 
So is this what my codes should look like?

Form:
Code:
	<div id="comments_wrap">
	<?php include("comment_display.php"); ?>
	

		<form method="post" action="comment_process.php">
		
			<label for="name">Name</label>
			<input type="text" name="name" value="" />
			
			<label for="website">Website</label>
			<input type="text" name="website" value="" />
			
			<label for="comment">Comment</label>
			<textarea rows="15" cols="5" name="comment"></textarea>
			
			<input type="submit" name="submit" value="Submit" id="submit" />
			
			
		
		</form>
		
		
	

	</div>

comment_process.php:
Code:
<?php

ini_set('display_errors', 1); // turn on error display 
ini_set('log_errors', 1);     // do log errors 
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'].'/.../php_errors.log');

if (isset($_POST['submit'])) {

    if (empty($_POST['name']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name and comment.");
    }
	$month = date("n");
	$day = date("j");
	$year = date("y");
	$hour = date("g");
	$minutes = date("i");
	
    $name = htmlspecialchars(strip_tags($_POST['name']));
    $website = htmlspecialchars(strip_tags($_POST['website']));
    $comment = htmlspecialchars(strip_tags($_POST['comment']));
    $comment = nl2br($comment);

    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
        $website = addslashes($website);
        $comment = addslashes($comment);


    }

     mysql_connect ('localhost', 'root', 'root') ;
    	mysql_select_db ('Blog');

    $result = mysql_query("INSERT INTO blog_comments (name,  website, comment, day, month, year, hour, minutes) VALUES ('$name','$website','$comment','$day','$month','$year','$hour','$minutes')") or print("Can't create the table 'php_blog_comments' in the database.<br />" . $sql . "<br />" . mysql_error());
    }

  ?>
  
  <html>
  <head>
  <meta HTTP-EQUIV="REFRESH" content="0; url=http://localhost:8888/blog_post.php#comments">
  </head>
  <body>
  </body>
  </html>

comment_display.php:
Code:
<?php

ini_set('display_errors', 1); // turn on error display 
ini_set('log_errors', 1);     // do log errors 
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'].'/.../php_errors.log');


	 mysql_connect ('localhost', 'root', 'root') ;
    	mysql_select_db ('Blog');
    	
    	$entry = basename(_FILE_);
    	
    	$post_id = mysql_query(SELECT id FROM blog_entries WHERE entry =  '$entry' LIMIT 1");
    	$row = mysql_fetch_assoc($post_id);
    	$post_id = $row['id'];
    	$query = mysql_query("SELECT * FROM `blog_comments` WHERE id='$post_id'");
    
    
    while($row = mysql_fetch_assoc($query)) {
    $date = $row["month"].'.'.$row["day"].'.'.$row["year"]; 
    $time = $row["hour"].':'.$row["minutes"];
       
     echo 
     ' <div id="comment_'.$row["id"].'" class="comment">
     <div class="details">'.$row["name"].'<br>'.$date.'<br>'.$time.'</div>
     <div class="v_line"></div>
     <div class="message">'.$row["comment"].'</div>
     </div>';
     }
  ?>

Is that right? I feel like I'm missing something...
 
Someone please chime in in on this. I'm building my PHP/MySQL blog as well so your help can help both OP and myself.

OP, I noticed your DB connects are different than mine. Maybe that is causing some issues? What's the difference between OP's implementation:
Code:
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('Blog');
and mine:
Code:
$link = mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('Blog', $link);
 
You've got some issues in your comment_display.php file.
  • The __FILE__ part has 2 underscores on each side of it.
  • You are missing an opening double quote on the first query.
  • Those php_ini() at the top don't work here because they aren't at the top of the entire file. The comment_display.php file is included into another file further down the page so that's why they don't work here.
  • It looks like you are keeping date/time components in separate pieces. This isn't necessary. MySQL has a DATETIME data type that does everything you will need. I'll let you look into that, but it's pretty easy. That's not causing a problem, but just a tip for efficient code.
  • Below I'm showing a more efficient way to do that echo using a heredoc method.
PHP:
<?php
// comment_display.php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('Blog');
  
$entry = basename(__FILE__);
    	
$post_id = mysql_query("SELECT id FROM blog_entries WHERE entry =  '$entry' LIMIT 1");
$row = mysql_fetch_assoc($post_id);
$post_id = $row['id'];
$query = mysql_query("SELECT * FROM `blog_comments` WHERE id='$post_id'");
    
while($row = mysql_fetch_assoc($query)) {
  //$date = $row["month"].'.'.$row["day"].'.'.$row["year"]; 
  //$time = $row["hour"].':'.$row["minutes"];
  $date = date('m.d.Y', strtotime($row['date']));
  $time = date('h:m', strtotime($row['date']));
  
  echo <<<AAA
  <div id="comment_{$row['id']}" class="comment">
  <div class="details">{$row['name']}<br>$date<br>$time</div>
  <div class="v_line"></div>
  <div class="message">{$row['comment']}</div>
  </div>
AAA;
}
?>
In your form you'll want a line like,
HTML:
<input type="hidden" name="entry" value="<?php echo $post_id; ?>" />
That puts the blog post id in a hidden form field so you can make use of it when adding the comment to the DB.

For the comment_process.php file.
  • On the ini_set() line, you want to use .. rather than ... Two dots means go up a directory. 3 dots means a file with the name ...
  • I showed how to do a better redirect using PHP at the bottom.
  • I've made some comments in the code as well.
PHP:
<?php
// comment_process.php
ini_set('display_errors', 1); // turn on error display 
ini_set('log_errors', 1);     // do log errors 
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'].'/../php_errors.log');

if (isset($_POST['submit'])) {
  if (empty($_POST['name']) || empty($_POST['comment'])) {
      die("You have forgotten to fill in one of the required fields! Please make sure you submit a name and comment.");
  }
  // This is an inefficient way to get date
// 	$month = date("n");
// 	$day = date("j");
// 	$year = date("y");
// 	$hour = date("g");
// 	$minutes = date("i");
	
  $name = htmlspecialchars(strip_tags($_POST['name']));
  $website = htmlspecialchars(strip_tags($_POST['website']));
  $comment = htmlspecialchars(strip_tags($_POST['comment']));
  $comment = nl2br($comment);
  // New part
  $entry = htmlspecialchars(strip_tags($_POST['entry']));

  if (!get_magic_quotes_gpc()) {
      $name = addslashes($name);
      $website = addslashes($website);
      $comment = addslashes($comment);
  }

  mysql_connect ('localhost', 'root', 'root') ;
  mysql_select_db ('Blog');

  //$result = mysql_query("INSERT INTO blog_comments (name,  website, comment, day, month, year, hour, minutes) VALUES ('$name','$website','$comment','$day','$month','$year','$hour','$minutes')") or die("Can't create the table 'php_blog_comments' in the database.<br />" . "<br />" . mysql_error());
  
  // This query makes use of the post id ($entry) and shows how you would put
  // the current date and time into the DB field
  $result = mysql_query("INSERT INTO blog_comments
    (post_id, name, website, comment, date)
    VALUES ('$entry', '$name', '$website', '$comment', DATETIME('NOW'))")
    or die ("Can't create the table 'php_blog_comments' in the database.<br />"
    . "<br />" . mysql_error());
}
// Redirect user back to page at comments section
header('Location: '. $_SERVER['HTTP_REFERER'].'#comments');
?>

OP, I noticed your DB connects are different than mine. Maybe that is causing some issues? What's the difference between OP's implementation:

They're equivalent in this context. The 2nd parameter is optional for mysql_select_db. It's only needed when you have multiple MySQL connections open and need to ensure you selecting the DB on the right connection.
 
In your form you'll want a line like,
HTML:
<input type="hidden" name="entry" value="<?php echo $post_id; ?>" />
That puts the blog post id in a hidden form field so you can make use of it when adding the comment to the DB.

If there are multiple post_id's how does it choose the correct one? Do I need to hardcode that somewhere, or am I missing something?
 
If there are multiple post_id's how does it choose the correct one? Do I need to hardcode that somewhere, or am I missing something?

This line,
PHP:
$entry = basename(__FILE__);
Gets the file name of the current page. From what I've gathered, you're writing individual files for each blog post e.g., blog_post_1.php, blog_post_2.php, etc. So, $entry will be dependent on the current page being viewed. That file name is in the DB (the blog_entries table) and that is searched out with this query,
PHP:
$post_id = mysql_query("SELECT id FROM blog_entries WHERE entry = '$entry' LIMIT 1");
The LIMIT 1 part makes sure only record gets returned because I'm assuming you won't use the same file name for a post. Does that clear it up?
 
Ok, I get it now..I'm looking through my comment display script..something weird is happening there because nothing after it is showing up.
 
Ok, I get it now..I'm looking through my comment display script..something weird is happening there because nothing after it is showing up.

Do you mean the comments show, but the comment form doesn't? When you view the source code in the browser, what is the last stuff being outputted? Remember we can't see what you can and don't know what you're updated code looks like so details are needed when you run into issues.
 
Just as a heads up, when I first implemented my blog I had a lot of spam-bots posting crap. I would suggest implementing a CAPTCHA technique to decrease the amount of bot-posts you may receive. There a lot of tutorials out there, just search for it. PM me if you want some tips when the time comes.
 
THIS IS KILLING ME!:eek:

Ok, so I had to adjust the code you gave me a little bit to get it working with my database. Just a quick rundown:
  • post_id is a row on the comments table; it defines the post that the comment should appear on via the entry_id.
  • entry_id is a row on the entries table. It is auto incremented for each post.
  • title is a row on the entries table; it is manually set and has the same name as the file name

I had to remove your DATETIME('NOW') as well as the heredoc part because they were causing errors and preventing the page from displaying completely. right now, all the comments are being displayed on all posts.

Here are my codes (parts in red were changed by me)

comments_process.php:
Code:
<?php 
// comment_process.php 
ini_set('display_errors', 1); // turn on error display  
ini_set('log_errors', 1);     // do log errors  
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'].'/../php_errors.log'); 

if (isset($_POST['submit'])) { 
  if (empty($_POST['name']) || empty($_POST['comment'])) { 
      die("You have forgotten to fill in one of the required fields! Please make sure you submit a name and comment."); 
  } 

   [COLOR="Red"]  $month = date("n"); 
     $day = date("j"); 
     $year = date("y"); 
     $hour = date("g"); 
     $minutes = date("i"); [/COLOR]
     
  $name = htmlspecialchars(strip_tags($_POST['name'])); 
  $website = htmlspecialchars(strip_tags($_POST['website'])); 
  $comment = htmlspecialchars(strip_tags($_POST['comment'])); 
  $comment = nl2br($comment); 
  // New part 
  $entry = htmlspecialchars(strip_tags($_POST['entry'])); 

  if (!get_magic_quotes_gpc()) { 
      $name = addslashes($name); 
      $website = addslashes($website); 
      $comment = addslashes($comment); 
  } 

  mysql_connect ('localhost', 'root', 'root') ; 
  mysql_select_db ('Blog'); 

  //$result = mysql_query("INSERT INTO blog_comments (name,  website, comment, [COLOR="red"]day, month, year, hour, minutes[/COLOR]) VALUES ('$name','$website','$comment','$day','$month','$year','$hour','$minutes')") or die("Can't create the table 'php_blog_comments' in the database.<br />" . "<br />" . mysql_error()); 
   
  // This query makes use of the post id ($entry) and shows how you would put 
  // the current date and time into the DB field 
 $result = mysql_query("INSERT INTO blog_comments (name,  website, comment[COLOR="red"], day, month, year, hour, minutes[/COLOR], [COLOR="red"][U]post_id[/U][/COLOR]) VALUES ('$name','$website','$comment',[COLOR="red"]'$day','$month','$year','$hour','$minutes','$entry[/COLOR]')") or print("Can't create the table 'php_blog_comments' in the database.<br />" . $sql . "<br />" . mysql_error()); 
} 
// Redirect user back to page at comments section 
header('Location: '. $_SERVER['HTTP_REFERER'].'#comments'); 
?>

comments_display.php
Code:
<?php 
 
mysql_connect ('localhost', 'root', 'root'); 
mysql_select_db ('Blog'); 
   
$entry = basename(__FILE__); 
         
$post_id = mysql_query("SELECT [COLOR="red"]entry_id[/COLOR] FROM blog_entries WHERE [COLOR="red"]title[/COLOR] = '$entry' LIMIT 1"); 
$row = mysql_fetch_assoc($post_id); 
$post_id = $row['[COLOR="red"]entry_id[/COLOR]']; 
$query = mysql_query("SELECT * FROM `blog_comments` WHERE [COLOR="red"]post_id[/COLOR]='$post_id'"); 
     
while($row = mysql_fetch_assoc($query)) { 
  $date = $row["month"].'.'.$row["day"].'.'.$row["year"];  
  $time = $row["hour"].':'.$row["minutes"]; 
   
[COLOR="red"]     echo 
     ' <div id="comment_'.$row["id"].'" class="comment">
     <div class="details">'.$row["name"].'<br>'.$date.'<br>'.$time.'</div>
     <div class="v_line"></div>
     <div class="message">'.$row["comment"].'</div>
     </div>';[/COLOR]
} 
?>

Did I mess up? Anyways, you've been a HUGE help (I honestly can't thank you enough) and I'm sure we'll be able to get this working!
 
Part of that was probably my fault. Some of the code wasn't necessarily copy and paste proof. I was advising some changes that would also require making changes in the DB before they would be usable. So I threw a bit at you at once.

At the moment, the only problem I see is in the comments_display.php on the last query part after the "or print" part you reference a $sql variable, which doesn't exist, and was why I removed it from the code I wrote in, though I never called that out to you. It's likely leftover from when you may have created the query separately as its own variable.

So the comments are getting outputted. So that means it stops just before this line?
HTML:
<form method="post" action="comment_process.php">

Bostonaholic said:
Just as a heads up, when I first implemented my blog I had a lot of spam-bots posting crap. I would suggest implementing a CAPTCHA technique to decrease the amount of bot-posts you may receive.
While spam blocking is a good thing to address, it's not the right time for him to start worrying about it. I also really hate the CAPTCHA stuff so always advise against it (mostly because of accessibility issues). I stop 100% of the spam on my contact form and don't use any CAPTCHA. I haven't gotten my write-up of techniques completed yet, but is in progress.
 
While spam blocking is a good thing to address, it's not the right time for him to start worrying about it. I also really hate the CAPTCHA stuff so always advise against it (mostly because of accessibility issues). I stop 100% of the spam on my contact form and don't use any CAPTCHA. I haven't gotten my write-up of techniques completed yet, but is in progress.

I look forward to reading your write-up. Maybe you'll inspire me to change my spam blocking method as well.

I only mentioned it because it was only a matter of weeks before my blog was discovered by the bots.
 
No, everything is getting displayed, that's part of the problem, EVERYTHING is getting displayed on EVERY post. What do I have to change in the database (is anything)

P.S. I fixed the problem earlier of the whole page not being displayed, something in your heredoc was messing it up. I'll look at that later.. for now I just want the thing to work
 
No, everything is getting displayed, that's part of the problem, EVERYTHING is getting displayed on EVERY post. What do I have to change in the database (is anything)

P.S. I fixed the problem earlier of the whole page not being displayed, something in your heredoc was messing it up. I'll look at that later.. for now I just want the thing to work

OK, if I'm reading correctly, you're saying that no matter what blog post you view you see all comments, including comments for other blog posts. This is where debugging tricks are helpful. A common, and simple method to use, is to do echo statements to see what queries are really being sent to the DB. So, in the comments display file after this line do,
PHP:
$post_id = mysql_query("SELECT entry_id FROM blog_entries WHERE title = '$entry' LIMIT 1"); 
echo "SELECT entry_id FROM blog_entries WHERE title = '$entry' LIMIT 1";
and see what gets outputted to see if the variables are what you expect them to be. Do that for the other queries too. As a part of MAMP it also installs phpMyAdmin, which allows you to take a look at your DB with a web interface. Likely located at http://localhost:8888/phpMyAdmin/ or maybe http://localhost:8888/phpMyAdminForPHP5/ then you can browser the tables and see if the correct data is in there.
 
No, everything is getting displayed, that's part of the problem, EVERYTHING is getting displayed on EVERY post. What do I have to change in the database (is anything)

P.S. I fixed the problem earlier of the whole page not being displayed, something in your heredoc was messing it up. I'll look at that later.. for now I just want the thing to work

It looks like your SELECT statement in comments_display.php is correct for grabbing the comments for the supplied blog entry. Have you looked at the actual data for the comments? Be sure that each comment is correctly referencing the associated blog entry.
 
Ok....

I did what you said, with the echo after the SELECT statement, but that just printed the line as a string, then I thought maybe you meant for me to echo $query, but that didn't display anything. Did I miss something?

I looked and PhpAdmin, and the post_id is 0 on all comments.

Any ideas on what might be causing this?
 
Ok....

I did what you said, with the echo after the SELECT statement, but that just printed the line as a string, then I thought maybe you meant for me to echo $query, but that didn't display anything. Did I miss something?

I looked and PhpAdmin, and the post_id is 0 on all comments.

Any ideas on what might be causing this?

So that's our culprit right there. I'm in bed on my iPhone so I can't help much right now. The issue is most likely in your process_comments.php. What about your blog post ids in your blog entries table, are they incrementing correctly?
 
I did what you said, with the echo after the SELECT statement, but that just printed the line as a string, then I thought maybe you meant for me to echo $query, but that didn't display anything. Did I miss something?
That's exactly what it's suppose to do, print a string of the query. It's a sanity check kind of thing.

I looked and PhpAdmin, and the post_id is 0 on all comments.

Any ideas on what might be causing this?

It sounds like the entry_id field on the blog_entries table isn't set to auto increment. I believe you said you have been manually adding to this table?
 
That value is set to auto increment and the posts have the appropriate values. I have been adding the titles manually.

Geez I hate PHP...but it'll all be worth it...hopefully.
 
Hmm. Lets trace post_id from the insertion back.
  1. At the insert query $entry is what's being added to the DB
  2. $entry comes from the form
    HTML:
    <input type="hidden" name="entry" value="<?php echo $post_id; ?>" />
  3. $post_id comes from
    PHP:
    $post_id = $row['entry_id'];
  4. And so lets further examine this code block,
PHP:
$entry = basename(__FILE__);
$post_id = mysql_query("SELECT entry_id FROM blog_entries WHERE title = '$entry' LIMIT 1"); 
$row = mysql_fetch_assoc($post_id); 
$post_id = $row['entry_id'];
Notice how you're reusing the $post_id variable. That's probably not a good idea. You can also try a echo on some of the variables from this block, like $entry, the $row['entry_id'], and the query to see what their values are.
 
Ok, when I echoed the query, I got the following result:

Resource id #5

Not sure what that means, but I don't think its what it should be. Also, when you say that I'm reusing post_id where are you referring to? Is it this line:
Code:
$post_id = $row['entry_id'];

I didn't think I could take anything out. Of course, I could very well be wrong.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.