Page 1 of 1

PHP tutorial: Blog (including commenting)

Posted: Tue Feb 19, 2013 10:26 am
by ericjric
I nearly have everything working except for new comment submissions. When I run the blog_read.php file I get an error message that we defined ourselves in the tutorial "Invalid Post ID." I have been troubleshooting for quite a while already and haven't come up with anything relating to this issue. My code matches the videos' exactly. Any help will be appreciated greatly as I am new to this and need a little nudge in the right direction. Cheers!


blog_read.php

<?php
include('core2/init.inc.php');

if (isset($_GET['pid'], $_POST['user'], $_POST['body'])) {
	if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])) {
		header("Location: blog_read.php?pid={$_GET['pid']}");
	}else {
		header('Location: blog_list.php');
	}
	die();
}

?>

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Blog Tutorial</title>
	</head>
	<body>
		<div>
			<?php			
			if (!isset($_GET['pid']) || valid_pid($_GET['pid']) !== true) {
				echo 'Invalid post ID.';
			} else {
				$post = get_post($_GET['pid']);	
			?>
			
			
			<h2><?php echo $post['title']; ?></h2>
			<h4>By <?php echo $post['user']; ?> on <?php echo $post['date']; ?> (<?php echo count($post['comments']); ?> comments)</h4>
			
			<hr />
			
			<p><?php echo $post['body']; ?></p>
			
			<hr />
			<?php
				foreach ($post['comments'] as $comment) {
					?>
					<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
					<p><?php echo $comment['body']; ?></p>
					<hr />	
					<?php
				}
			?>

			<form action="blog_read.php" method="POST">
				<p>	
					<label for="user">Name</label>
					<input type="text" name="user" id="user" maxlength="50" />
				</p>
				<p>
					<textarea name="body" rows="20" cols="60"></textarea>
				</p>
				<p>
					<input type="submit" value="Add Comment" />
				</p>
			</form>	
			<?php
			}
			
			?>
		</div>
		
	</body>
</html>
blog_post.php

<?php
include('core2/init.inc.php');

if (isset($_POST['user'], $_POST['title'], $_POST['body'])) {
	add_post($_POST['user'], $_POST['title'], $_POST['body']);
	header('Location: blog_list.php');
	die();
}

?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Blog</title>
	</head>
	<body>
		<form action="" method="POST">
			<p>
				<label for="user">Name</label>
				<input type="text" name="user" id="user" />
			</p>
			<p>
				<label for="title">Title</label>
				<input type="text" name="title" id="title" />
			</p>
			<p>
				<textarea name="body" rows="20" cols="60"></textarea>
			</p>
			<p>
				<input type="submit" value="Add Post" />
			</p>
		</form>
	</body>
</html>
blog_list.php
<?php
include('core2/init.inc.php');


?>

<!DOCTYPE html>
<html lan="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>PHP Blog</title>
	</head>
	<body>
		<div>
			<?php
			
			$posts = get_posts();
			
			foreach ($posts as $post) {
				?>
				<h2><a href="blog_read.php?pid=<?php echo $post['id']; ?>"><?php echo $post['title']; ?></a></h2>
				<h4>By <?php echo $post['user']; ?> on <?php echo $post['date']; ?></h4>
				<h4>(<?php echo $post['total_comments']; ?> comments, last comment posted: <?php echo $post['last_comment']; ?>)</h4>
				
				<hr />
				
				<p><?php echo $post['preview']; ?></p>
				<?php	
			}
			?>
		</div>
	</body>
</html>
post.inc.php
<?php

//checks if the given post id is in the table.
function valid_pid($pid) {
	$pid = (int)$pid;  //making this an integer drops everything that isn't a number and helps prevent sql injection.
	
	$total = mysql_query("SELECT COUNT(`post_id`) FROM `posts` WHERE `post_id` = {$pid}"); //COUNT counts the number of rows in the results and returns that in a single cell.
	$total = mysql_result($total, 0);
	
	if ($total != 1) {
		return false;
	} else{
		return true;
	}
}

//fetches a summary of all the blog posts.
function get_posts () {
	$sql = "SELECT
				`posts`.`post_id` AS `id`,
				`posts`.`post_title` AS `title`,
				LEFT(`posts`.`post_body`, 512) AS `preview`,
				`posts`.`post_user` AS `user`,
				DATE_FORMAT(`posts`.`post_date`, '%d/%m/%Y @ %H:%i:%s') AS `date`,
				`comments`.`total_comments`,
				DATE_FORMAT(`comments`.`last_comment`, '%d/%m/%Y @ %H:%i:%s') AS `last_comment`
			FROM `posts`
			LEFT JOIN (
				SELECT
					`post_id`,
					COUNT(`comment_id`) AS `total_comments`,
					MAX(`comment_date`) AS `last_comment`
				FROM `comments`
				GROUP BY `post_id`
			) AS `comments`
			ON `posts`.`post_id` = `comments`.`post_id`
			ORDER BY `posts`.`post_date` DESC";
	
	$posts = mysql_query($sql);
	
	$rows = array();
	while (($row = mysql_fetch_assoc($posts)) !== false) {
		$rows[] = array(
			'id' 				=> $row['id'],
			'title' 			=> $row['title'],
			'preview' 			=> $row['preview'],
			'user' 				=> $row['user'],
			'date' 				=> $row['date'],
			'total_comments' 	=> ($row['total_comments'] === null) ? 0 : $row['total_comments'],
			'last_comment'		=> ($row['last_comment'] === null) ? 'never' : $row['last_comment']
		);
	}
	
	return $rows;
}

//fetches a single post from the table.
function get_post($pid) {
	$pid = (int)$pid;
	
	$sql = "SELECT
				`post_title` AS `title`,
				`post_body` AS `body`,
				`post_user` AS `user`,
				`post_date` AS `date`
				FROM `posts`
				WHERE `post_id` = {$pid}";
				
	$post = mysql_query($sql);
	$post = mysql_fetch_assoc($post);
	
	$post['comments'] = get_comments($pid);
	
	return $post;
}

//adds a new blog entry.
function add_post($name, $title, $body) {
	$name  = mysql_real_escape_string(htmlentities($name));	
	$title  = mysql_real_escape_string(htmlentities($title));
	$body  = mysql_real_escape_string(nl2br(htmlentities($body))); //nl2br() convert any new lines into line break tags. mysql_real_escape_string() escapes new lines, so that is why we add the nl1br() function inside it.
	
	mysql_query("INSERT INTO `posts` (`post_user`, `post_title`, `post_body`, `post_date`) VALUES ('{$name}', '{$title}', '{$body}', NOW())");
}
mysql_error();

?>
comment.inc.php
<?php

//fetches all of the comments for a given blog post.
function get_comments($pid) {
	$pid = (int)$pid;
	$sql = "SELECT
				`comment_body` AS `body`,
				`comment_user` AS `user`,
				DATE_FORMAT(`comment_date`, '%d/%m/%Y @ %H:%i:%s') AS `date`
				FROM `comments`
				WHERE `post_id` = {$pid}";
	
	$comments = mysql_query($sql);
	
	$return = array();
	while (($row = mysql_fetch_assoc($comments)) !== false) {
		$return[] = $row;	
	}
	return $return;
}

//adds a comment.
function add_comment($pid, $user, $body) {
	if (valid_pid($pid) === false) {
		return false;
	}
	
	$pid = (int)$pid;
	$user = mysql_real_escape_string(htmlentities($user));
	$body = mysql_real_escape_string(nl2br(htmlentities($body)));
	
	mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
	return true;
}
?>
init.inc.php
<?php
error_reporting(E_ALL);
	mysql_connect('127.0.0.1', 'xxxx', 'xxxx');
	mysql_select_db('blog');
	
	
	require('inc/comment.inc.php');
	require('inc/posts.inc.php');	
?>

Re: PHP tutorial: Blog (including commenting)

Posted: Tue Feb 19, 2013 2:06 pm
by ExtremeGaming
Are you actually going to the page with pid in the url? ex: http://domain.com/blog.php?pid=1

If so, does the pid exist in the database?

If that doesn't work try making a new page and visit it like you would the blog page.

Put the following in it:
<?php
include('core2/init.inc.php');

// Test if you are using the url correctly.
if(isset($_GET['pid'])) {
	// Since this is a test page, I'm not worried about sql injection
	$pid = $_GET['pid'];
	echo "URL test successful.<br />";
} else {
	die('pid is not set in the url.  Please do so to continue.');
}
	
// Test your query
$total = mysql_query("SELECT COUNT(`post_id`) FROM `posts` WHERE `post_id` = {$pid}");

if(mysql_error()) {
	die('<p>It seems you have an error in your query.  The following occurred:<br/><b>'.mysql_error().'</b></p>');
} else {
	echo "Query test successful.<br />";
}

// If the query was successful, now we check the result.
$total = mysql_result($total, 0);

if($total != 1) {
	die("It seems you have an error in your database.  Your query returned the following amount of rows: <b>$total</b>");
} else {
	echo "Query result test successful.<br />";
}

echo "All obvious tests passed.  It seems this needs to be looked into further.";

?>

Re: PHP tutorial: Blog (including commenting)

Posted: Wed Feb 20, 2013 6:31 am
by ericjric
I figured it out in the end, it was something stupid. on my form action="" i'm used to putting in the page i'm coding on (ie: blog_read.php if that is the page the form is on). In the tutorial he has this field blank (<form action="" method="POST">). After I fixed this it worked perfectly.

Just clearing data that I mistakenly placed in the quotes next to action fixed this problem for me.
<form action="" method="post">