PHP Comments Code

Discussion in 'Web Design and Development' started by iMasterWeb, Nov 24, 2009.

  1. iMasterWeb macrumors regular

    Joined:
    Mar 15, 2009
    #1
    Hi! Ok, so if any of you (*cough* Angelwatt *cough*) have been following my previous posts, you'll know that I'm creating my first blog. Right now, I'm at the point of adding the comments. I've looked at numerous tutorials and have managed to scrape up a code. Of course, it doesn't work, but that's why I'm here. WHat happens is, when you submit the comment, it redirects you to "comments_process.php" instead of displaying the comment. So here we go:

    The form:
    Code:
    	<div id="comments_wrap">
    	
    
    		<form method="post" action="comment_process.php">
    			<input type="hidden" name="entry" value="blog_post.html" />
    		
    			<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>
    		
    		<?php include("comment_display.php"); ?>
    	
    
    	</div>
    comment_process.php:
    Code:
    <?php
    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.");
        }
    
        $entry = htmlspecialchars(strip_tags($_POST['entry']));
        $name = htmlspecialchars(strip_tags($_POST['name']));
        $webste = 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', '*********', '*********') ;
        mysql_select_db ('*********');
    
        $result = mysql_query("INSERT INTO php_blog_comments (entry,  name,  website, comment, timestamp) VALUES ('$entry','$name','$website','$comment','$timestamp')");
        }
    
      ?>
    comment_display.php:
    Code:
    <?php
    	 mysql_connect ('localhost', '******', '******') ;
        	mysql_select_db ('******');
    	
    	    $query = mysql_query("SELECT * FROM `php_blog_comments` WHERE entry='$entry'");
        while($row = mysql_fetch_assoc($query)) {
         echo '
         <div id="comment_'.$row['id'].';">
         <strong>'.$row['name'].'</strong> Says,
         '$row['comment'].'
         </div>';
         }
      ?>
    This site is temporarily live for testing purposes: http://imasterweb.net/blog_post.php

    Please be gentle as I am an EXTREME beginner. Thanks a ton!!!!

    -iMaster
     
  2. rowsdower macrumors 6502

    Joined:
    Jun 2, 2009
    #2
    The browser takes you to the "action" url of the form when you click the submit button. I assume you want the user to remain on the blog post page, but with his or her comment added. There are a few ways to do this.

    One way is to put a redirect back to the blog post into your comment_process.php script.

    Another way: Say that your blog post display PHP script (the one that contains the form you have attached here) is called "blog_post.php". Put the PHP code you have attached here towards the top of blog_post.php, and change the action of the form to blog_post.php (i.e. the action is the same script). I assume you already have code in that page to display previous comments on the blog post. In that case, when the user submits the form, blog_post.php will create a new comment, then display the post, then display all the comments including the new one.

    Another method is to use your comment_process.php script more or less as-is, and use Javascript/AJAX to submit the form and add the comment to the post page dynamically. This is the smoothest for the user, but probably also the most difficult to program.

    For now, I would just add the redirect to what you have and then you can think about AJAX when you're ready for it.
     
  3. rowsdower macrumors 6502

    Joined:
    Jun 2, 2009
    #3
    By the way, you should use addslashes (or mysql_real_escape_string) on $entry as well as $name, $website, and $comment. Even though the entry field is hidden in the form, the user can change it (e.g. using GreaseMonkey).
     
  4. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #4
    Thanks for the reply rosdower. I'll add that in later. One problem, however is that the comment isn't even being added to the database. Also, I found one careless mistake (I forgot to insert the code to actually display the comment) so that has been added to the initial post. Thanks for any help!

    EDIT: Another problem that I'm seeing is that anything after the code that includes comment_display.php doesn't show up...not even in the source code, but it IS there. Any particular reason for this? I'm missing my sidebar :(
     
  5. rowsdower macrumors 6502

    Joined:
    Jun 2, 2009
    #5
    There is probably a problem with your query, but it's hard to tell from just looking at the code. Depending on your webserver setup, PHP or MySQL errors might not show up on the page. I would echo the INSERT query so that you can see if there is a problem. Also, $result should be true if the query was successful and false if there was an error. You might want to check that and add a warning anyway.

    My guess is that there is some problem with your echo statement in comment_display.php. There are a lot of single quotes in there so it is hard to see exactly what is output and what is PHP code. One way to debug this is to start with an empty echo statement and add to it one piece at a time so that you can see that it works with each step.

    Do you normally get a PHP error displayed in the browser if you make a mistake (e.g. a typo) in your code? There may also be errors in the server logs that can give you some hints.
     
  6. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #6
    Well I found one trouble maker, can you make any sense of this error:

    Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

    I'm sure that this is part of the reason my script isn't working. And yes, all of my info is correct. My webhost is ByetHost, if it matters.
     
  7. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #7
    I notice you have an extra comma in your query (comment_process.php). It's highlighted in red below after timestamp.
    Code:
    INSERT INTO php_blog_comments (entry,  name,  website, comment, timestamp[COLOR="Red"][B],[/B][/COLOR]) VALUES ('$entry','$name','$website','$comment','$timestamp')
    That could potentially be causing the MySQL error you're seeing. It may also be something your web host needs to look into. I've gotten that type of error locally on my machine running MAMP. You may want to look into MAMP so you can test your site locally rather than trying to do it on the server where all can see it. That would allow you to turn errors on and see them in the browser so you can more easily track issues. It's pretty easy to setup and configure.

    Another query issue in comment_display.php. You need to use double quotes on the below query because you have single quotes in the query and you use a variable. A variable will only be processed when inside double quotes.
    Code:
    $query = mysql_query([COLOR="Red"]'[/COLOR]SELECT * FROM `php_blog_comments` WHERE entry=[COLOR="Red"][B]'[/B][/COLOR]$entry[COLOR="Red"][B]''[/B][/COLOR]);
    Also, in the same file, you have a ?> inside your echo statement, which ends PHP processing and is why your page stops prematurely most likely.

    That may not fix everything, but should get you closer.
     
  8. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #8
    Thanks Angel, I fixed those to errors on my code, and the samples posted above. Thanks for the suggestion about MAMP, downloading it now.
     
  9. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #9
    I got MAMP running, and have green lights on Apache and MySQL. I set up my database and everything except PHP files are working. I can't view my actual pages (such as blog_post.php) Any idea on what's going on. I've put them inside of the Htdocs folder, but they just appear as plain text in Safari. Thanks for the help!

    -iMaster
     
  10. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #10
    That's odd, it should process PHP files with the default setup. Check the httpd.conf file (MAMP/conf/apache/) for a line like,
    Code:
    AddType application/x-httpd-php .php .phtml
    That's what tells the server to process it as PHP. Also, how are you viewing the file, e.g., Are you opening the file directly in the browser (which would begin file://) or are you accessing it like http://localhost/file.php ? You'll want to do it the 2nd way as accessing the file directly doesn't let it get processed.
     
  11. Bostonaholic macrumors 6502

    Bostonaholic

    Joined:
    Aug 21, 2009
    Location:
    Columbus, Ohio
    #11
    To expand upon that. Make sure your MAMP settings are pointing to the parent directory of your page. Additionally, you'll want to visit http://localhost:8888/ to view your processed php files. MAMP defaults to port 8888 but you can set that up via the MAMP settings.
     
  12. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #12
    Ok, I got it to work! I ran a test and it worked...halfway. The comment is in the database :)D) but it didn't show up on the page..I'm looking at my code now.

    EDIT: I think I found my problem: On the SELECT line in comment_display.php it probably doesn't know what $entry is, because it isn't declared in that file and isn't a global variable. I read somewhere that global variables are not good for security. Can anyone shed some light on this or provide some alternatives?

    EDIT 2: It's still not displaying anything after the line that includes comment_display.php. I went through it and didn't see any errors, I changed some single quotes to double quotes. Is that ok, or could I be messing it up even more?
     
  13. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #13
    It would probably be good to see your updated code since it sounds like there has been a number of changes.

    To ensure error displaying is on, place the following PHP and the top of your 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'].'/../path/php_errors.log');
    Make sure to update the path in that last line. I generally place it above the htdocs folder so it can't be viewed by everyone. For the first line you would switch it from 1 to 0 to ensure errors are not displayed on your live site as a malicious person could use the information in error messages to attack your site. Another note, these settings can be changed in the php.ini file in MAMP, but you generally don't have access to that on your web host so that's why I usually set it in PHP files.
     
  14. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #14
    Here you go! (the form hasn't changed)

    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'].'/Applications/MAMP/php_errors.log');
    
    
    	 mysql_connect ('localhost', 'root', 'root') ;
        	mysql_select_db ('Blog');
    	
    	    $query = mysql_query("SELECT * FROM `blog_comments` WHERE entry='blog_post.html'");
        while($row = mysql_fetch_assoc($query)) {
         echo 
         ' <div id="comment_'.$row["id"].'">
         <strong>'.$row["name"].'</strong> Says,
         '$row["comment"].'
         </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'].'/Applications/MAMP/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.");
        }
    
        $entry = htmlspecialchars(strip_tags($_POST['entry']));
        $name = htmlspecialchars(strip_tags($_POST['name']));
        $webste = 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);
            $entry = addslashes($entry);
        }
    
         mysql_connect ('localhost', 'root', 'root') ;
        	mysql_select_db ('Blog');
    
        $result = mysql_query("INSERT INTO blog_comments (entry,  name,  website, comment, timestamp) VALUES ('$entry','$name','$website','$comment','$timestamp')") or print("Can't create the table 'php_blog_comments' in the database.<br />" . $sql . "<br />" . mysql_error());
        }
    
      ?>
    Thanks again!

    (P.S. It is very likely that I screwed up some of the quotes)
     
  15. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #15
    One quick thing about,
    PHP:
    ini_set('error_log'$_SERVER['DOCUMENT_ROOT'].'/Applications/MAMP/php_errors.log');
    $_SERVER['DOCUMENT_ROOT'] is the same as your htdocs folder. It's your website root. So for the location you want, you'll want to do,
    PHP:
    ini_set('error_log'$_SERVER['DOCUMENT_ROOT'].'/../php_errors.log');
    In the comment_process.php file you have a typo for the website variable. You missed the i.
    Code:
    $webs[COLOR="Red"][B]i[/B][/COLOR]te = htmlspecialchars(strip_tags($_POST['website']));
    In comment_display.php at the echo, you're missing a period right before $row["comment"]. Took me a while to see it. Syntax coloring doesn't catch that very well.
     
  16. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #16
    YAY! It works! At least now I have something to play with some CSS on. However, there's still the problem with $entry. I got it to work by replacing, in the SELECT line $entry with blog_post.html which is what the entry is set for for that page (hope that makes sense). But I need it to somehow do ths for me. One thing I thought was if there's some way to get the URL of a page I could use the page URL as the entry, that way it'd be automatic. Any other ideas? Thanks again guys!!
     
  17. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #17
    But of course there is. Essentially, you want the page that referred the post to your script. PHP can access the referrer page information.
    PHP:
    $_SERVER['HTTP_REFERER']
    Unfortunately, this doesn't always work (works 99% of the time though) as some security software blocks it or the user is using a addon that blocks it. The alternative is to add the page URL to the form using PHP so it gets sent along the same way as the other data. You would simply add it as a hidden form element. You would want to verify the page sent really exist though since it can be spoofed (see file_exists()). Though you would also need to change the blog post page to a .php file. You seemed to want to avoid that though. If you're adding the comment form to each page manually though you can add that hidden field easily enough. Just think it through to see what makes sense for your setup.
     
  18. Bostonaholic macrumors 6502

    Bostonaholic

    Joined:
    Aug 21, 2009
    Location:
    Columbus, Ohio
    #18
    In your entries table you should have a primary key associated with each post. Ideally this would be an INT that will AUTOINCREMENT each time a comment is inserted into the table. This way, selecting a comment is as easy as

    Code:
    SELECT * FROM blog_comments WHERE entry_id=$entry_id;
     
  19. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #19
    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.
     
  20. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #20
    Can you describe your DB setup so far.
    Example:
    Code:
    CREATE TABLE blog_comments (
      entry INT PRIMARY KEY,
      name VARCHAR(32),
      website VARCHAR(128),
      comment TEXT
    );
    You need a way to tie the blog posts to the comments. You can add another table that holds basic info about your posts without including the blog content.

    Code:
    CREATE TABLE blog_posts (
      id INT PRIMARY KEY,
      filename VARCHAR(128)
    );
    Then on the blog_comments table you would want to have a field named something like post_id and it would match up with the id on blog_posts. Hope that made sense.
     
  21. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #21
    Ok, basically I have the Name, website, etc. Then I have the Primary key which is id. This is auto-incremented for each comment. I have an entry row which is the name of the associated entry. Then I have the date, time, etc.

    I think I know what you're saying, though. I could make a second table with one row: post (or two as you have it above) and I could auto increment this for each post. Then, I could SELECT comments whose entry=post

    Is that right? If it is...how would I find which one matches up?

    Example: I modified my form code so that the value of entry is the page title. So then I'd have to go into my ENTRIES table and create a new row with the same name. Ok so then what? How do I connect the dots?


    ALSO: If anyone can provide useful articles about learning AJAX, or some ways to implement it in my scenario, it'd be appreciated. I'll have to use it eventually because I will post videos and reloading the page would be highly irritating. I've Googled like crazy but can't find anything useful. I've read what little information they have at w3schools, but there isn't much. Obviously, I have to get the comments working correctly first, but if you have any information its greatly appreciated. Thanks guys!!
     
  22. Bostonaholic macrumors 6502

    Bostonaholic

    Joined:
    Aug 21, 2009
    Location:
    Columbus, Ohio
    #22
    Why is it that you feel you need to use AJAX in your site for posting videos?

    TBH, I get the feeling you don't completely understand web technologies and you're trying to implement as many as possible. Maybe a better explanation of what you're trying to accomplish with the video posting and we can help you with what implementation would better suit your needs. Honestly, I don't believe posting a video is something that needs (or should use) the advantages of AJAX.

    But you're right, let's get the comments working first. Hopefully we can help you out. I too am writing my own PHP/MySQL blog (actually refactoring my 'beta' PHP blog) right now as well so this thread should be helpful to the both of us.
     
  23. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #23
    Here's an easy piece to find posts that belong to a specific blog post.
    PHP:
    $entry basename(__FILE__); // gets current file name
    $query mysql_query("SELECT * FROM `blog_comments` WHERE entry='$entry'");
    Ideally you'd want to match up on an id because if you ever want to change the file name of the blog post, you would need to change it in every file it was used, whereas an id wouldn't change and changing the file name part wouldn't hurt anything and would only need to be changed in one spot.

    I hadn't realized earlier that comment_display.php was be included in from your HTML blog post file. The ini_set() lines you have at the top of comment_display.php aren't actually being processed because they need to be at the top of the page, not just the top of the PHP block. Also, generally, unless you set it otherwise, .html files don't get processed for PHP content. Are you having any problem there?

    Currently you don't have a method to add blog posts into the DB. You're going to be creating the blog post files manually which means you'll need a way to add it into DB existence. The easiest way would be to add a PHP page with a form that would allow you to add it. Below is a basic form for this.
    HTML:
    <form action="add_blog_post.php" method="post">
    <fieldset>
      <legend>Add Blog Posts</legend>
      <input type="text" name="entry" id="entry" size="20" />
      <input type="submit" value="Add Blog Post" />
    </fieldset>
    </form>
    Then the PHP to process it.
    PHP:
    // add_blog_post.php
    if (!empty($_POST['entry'])) {
      
    $entry htmlspecialchars(strip_tags($_POST['entry']));
      
    // Check if that file exists
      
    if (file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$entry)) {
        
    // Grab just the file name
        
    $entry basename($entry);
        
    // Create query to add it in
        
    $sql "INSERT INTO blog_posts (filename) VALUES ($entry)";
      }
    }
    So for this, it would be a form with one text field for the file name location. With the way it's currently coded you would give the full path to the file from the root e.g., blog/post_123.html. If everything is going to be in a single folder then you can modify the code above to point directly to that folder when it does the file_exists() check. The code I've been provided also assumes all posts are in a single directory.

    You want to make sure this form is protected so other people can't add posts. You can try for security through obscurity and make sure you never link to that file or you can password protect it with PHP. Or you can place it in some admin folder and use .htaccess to add a password to that directory to protect it.

    Hopefully things make more sense. It should give you something to work with for a little while. Don't worry about AJAX for a while. It'll just get in the way for now.
     
  24. iMasterWeb thread starter macrumors regular

    Joined:
    Mar 15, 2009
    #24
    I agree, and I think that that's what I'm going to try to do. The thing that's been stumping me is how to increment the post_id on the comments without it incrementing for e very single comment. Would I have to do it manually? There should be some way to do it...maybe Javascript?

    Actually, all my files are PHP files for that exact reason.
     
  25. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #25
    I don't quite get what you're having issues with. The post_id will increment on its own as you add new blog posts. The comments will simply reference that post_id. The comments have their own id though that's unique to its table. JavaScript won't be of help.

    Code:
    CREATE TABLE blog_comments (
      id INT PRIMARY KEY AUTO INCREMENT,
      post_id INT,
      ...
    );
     

Share This Page