Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Blog Design Solutions (2006)

.pdf
Скачиваний:
39
Добавлен:
17.08.2013
Размер:
38.67 Mб
Скачать

B L O G D E S I G N S O L U T I O N S

} while ($myposts = mysql_fetch_array($result));

}else {

echo "<p>I haven't posted to my blog yet.</p>";

}

?>

This code steps through the MySQL array as in the CMS blog list page, but this time I’m using different HTML to present the post details. The post itself is unformatted so you can (indeed, you should) add all the HTML you require (paragraphs, links, emphasis, and so on) when you enter the post in the CMS. Later on, I will show you how you can automate some of that process so paragraph tags are automatically generated.

Next to insert is code that will enable the posts summary in the sidebar. Replace the comment <!-- a list of recent post titles will go here --> with this code:

<?php mysql_data_seek($result, 0);

$myposts = mysql_fetch_array($result);

if($myposts) { echo "<ul>\n"; do {

$post_id = $myposts["post_id"]; $title = $myposts["title"];

echo "<li><a href='post.php?post_id=$post_id' rel='bookmark'> $title</a></li>\n";

} while ($myposts = mysql_fetch_array($result)); echo "</ul>";

}

?>

As you might expect, this code is almost the same, but there is one crucial addition:

mysql_data_seek($result, 0);

$myposts = mysql_fetch_array($result);

These initial two lines reset the internal row pointer of the MySQL result to the beginning (row 0), so the do-while loop can start at the first post again. This saves the server from unnecessarily querying the database a second time.

Automatically formatting posts

As I said earlier, you will need to add the required HTML to all your blog posts so they are formatted with paragraphs, links, and so on. I’m sure you’d agree that it would be much easier if line breaks and paragraph tags were automatically added to your posts, so now I’ll show you a quick function to will do just that:

<?php

function format($text) {

$text = "<p>" . $text . "</p>"; $search = array("\r", "\n\n", "\n");

306

W R I T E Y O U R O W N B L O G E N G I N E

$replace = array("","</p><p>", "<br />"); $text = str_replace($search, $replace, $text); return $text;

}

?>

The user-defined format function makes use of the PHP str_replace search and replace function to replace line breaks in your posts with <br /> tags, and two line breaks in a row with paragraph tags. Because this function will be useful throughout your blog, save it to your blog root directory in a file called functions.php.

Stepping through the script:

function format($text) {

The format function accepts an argument called $text, which will be the unformatted post pulled from the database:

$text = "<p>" . $text . "</p>"; $text = stripslashes($text);

First, the whole post text is wrapped inside paragraph tags and then any slashes are

 

removed:

7

 

$search = array("\r", "\n\n", "\n");

 

$replace = array("","</p><p>", "<br />");

 

$search is an array (think of it as a list) of the text we need to replace in the post.

 

$replace is the corresponding array of text that will take its place. The first substitution

 

performed is to strip out all carriage return characters, as line breaks on Windows

 

machines are represented by two characters: a carriage return (\r) followed by a new line

 

character (\n). Then double-line breaks are replaced with a closing and opening paragraph

 

tag to create a new paragraph. The final substitution is to replace any remaining line

 

breaks with <br /> tags.

 

$text = str_replace($search, $replace, $text);

 

return $text;

 

Finally, the search and replace arrays are passed along with the text to the str_replace

 

function to perform the actual substitution and the resulting text is returned to wherever

 

the function was called.

 

Now call the functions.php include in your blog homepage by adding include

 

("functions.php"); to the PHP script just after the opening <?php delimiter at the very

 

top of your index.php page. Finally, you can call the format function to format your blog

 

post by making this change to your do-while loop:

 

$post = format($myposts["post"]);

 

307

B L O G D E S I G N S O L U T I O N S

Headers, footers, and other reusable elements

In the previous section, you created an include file called functions.php that can be reused in any page of your blog. It is useful to put all repeated parts of your code into includes so they can be easily updated if site-wide changes are required further down the line. The header, footer, and search form used in the index.php page will be reused throughout the site, so create the following include files.

First, save this header code as header.php:

<div id="header"> <h1>Samuel's Blog</h1> </div>

And replace this code in index.php with <?php include("header.php"); ?>. Now do the same with the footer by creating footer.php from this code:

<div id="header">

<h1><a href="index.php">Samuel's Blog</a></h1> </div>

And create searchform.php from this code:

<form action="search.php" method="get"> <h3 id="search">Search</h3>

<p>

<input type="text" name="q" value="" /> <input type="submit" value="Search" /> </p>

</form>

<h3 id="viewarchive"><a href="archive.php">View the Archive</a></h3>

After you replace the footer and search code in your index.php file, you should end up with this complete source listing:

<?php

include("functions.php");

//Open connection to database include("db_connect.php");

//Select 5 most recent posts

$sql = "SELECT post_id, title, post, DATE_FORMAT(postdate, '%e %b %Y at %H:%i') AS dateattime FROM posts

ORDER BY postdate DESC LIMIT 5"; $result = mysql_query($sql);

$myposts = mysql_fetch_array($result); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

308

W R I T E Y O U R O W N B L O G E N G I N E

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>Samuel's Blog</title> <style type="text/css"> @import url(blog.css); </style>

</head>

<body>

<?php include("header.php"); ?>

<!-- this is the main part of the page --> <div id="maincontent">

<div id="posts"> <?php if($myposts) {

do {

$post_id = $myposts["post_id"];

$title = $myposts["title"]; 7 $post = format($myposts["post"]);

$dateattime = $myposts["dateattime"];

echo "<h2 id='post$post_id'><a href='post.php?post_id=$post_id' rel='bookmark'>

$title</a></h2>\n";

echo "<h4>Posted on $dateattime</h4>\n"; echo "<div class='post'>$post</div>";

} while ($myposts = mysql_fetch_array($result));

}else {

echo "<p>I haven't posted to my blog yet.</p>";

}

?>

</div>

<div id="sidebar"> <div id="about"> <h3>About this</h3>

<p>This is a diary by Samuel Pepys.</p> </div>

<?php include("searchform.php"); ?>

<div id="recent"> <h3>Recent posts</h3> <?php

mysql_data_seek($result, 0);

$myposts = mysql_fetch_array($result);

309

B L O G D E S I G N S O L U T I O N S

if($myposts) { echo "<ul>\n"; do {

$post_id = $myposts["post_id"]; $title = $myposts["title"];

echo "<li><a href='post.php?post_id=$post_id' rel='bookmark'> $title</a></li>\n";

} while ($myposts = mysql_fetch_array($result)); echo "</ul>";

}

?>

</div>

</div>

<!-- sidebar ends -->

</div>

<!-- maincontent ends --> <?php include("footer.php"); ?> </body>

</html>

Creating a post page

In a blog, every post should have its own page. To enable this you will combine code from the blog homepage (index.php) and the CMS edit post page (addpost.php). Save this code as post.php in the root of your blog directory:

<?php

//Open connection to database include("db_connect.php");

//Get post_id from query string

$post_id = (isset($_REQUEST["post_id"]))?$_REQUEST["post_id"]:"";

// If post_id is a number get post from database if (preg_match("/^[0-9]+$/", $post_id)) {

$sql = "SELECT post_id, title, post, DATE_FORMAT(postdate, '%e %b %Y at %H:%i') AS dateattime FROM posts

WHERE post_id=$post_id LIMIT 1"; $result = mysql_query($sql);

$myposts = mysql_fetch_array($result);

}

include("functions.php");

?>

310

W R I T E Y O U R O W N B L O G E N G I N E

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>Samuel's Blog</title> <style type="text/css"> @import url(blog.css); </style>

</head>

<body>

<?php include("header.php"); ?>

<!-- this is the main part of the page --> <div id="maincontent">

<div id="posts"> <?php if($myposts) {

do { 7 $post_id = $myposts["post_id"];

$title = $myposts["title"]; $post = format($myposts["post"]);

$dateattime = $myposts["dateattime"]; echo "<h2>$title</h2>\n";

echo "<h4>Posted on $dateattime</h4>\n"; echo "<div class='post'>\n $post \n</div>";

} while ($myposts = mysql_fetch_array($result));

}else {

echo "<p>There is no post matching a post_id of $post_id.</p>";

}

?>

</div>

<div id="sidebar">

<?php include("searchform.php"); ?>

</div>

<!-- sidebar ends -->

</div>

<!-- maincontent ends -->

<?php include("footer.php"); ?></body> </html>

311

B L O G D E S I G N S O L U T I O N S

As with the edit post page in your CMS, the blog post page is called with a post_id in the query string so it knows which blog post to display. The blog homepage (index.php) you just created links to the post page like this: post.php?post_id=n where n is the post_id of a post. Clicking a link on your homepage should take you to a blog post that looks something like Figure 7-14 (if you haven’t already, make sure you have added some blog posts using your CMS).

Figure 7-14. The post page for your first blog post

At this point, you could have a little play by adding a few new posts through your CMS and see how they appear on the homepage and on their individual post pages.

Adding comments

One of the great attractions of blogging is allowing your readers to comment on what you have written. I’ll now show you how to add commenting to your blog engine.

Each comment will be stored in the database, so first you need to create a table in which to store the comments. Open up PHPMyAdmin in your browser. Select the database blog in the left side and then click the Structure tab. In the Create new table on database blog area, type comments into the Name input box and 7 into the Number of fields input box, as shown in Figure 7-15, then click Go.

312

W R I T E Y O U R O W N B L O G E N G I N E

Figure 7-15. Creating a new table

On the next screen, input the table definition for each field, as shown in Figure 7-16. Note that for the comment_id field you should also select auto_increment in the Extra column and click the primary column. This procedure ensures that each new comment automatically gets its own unique id number.

7

Figure 7-16. Creating the comments table in phpMyAdmin

Click Save and the table should be created—you will see comments added to the left column.

Now that you have a database table in which to store comments, you can add a form to collect comments and a script to insert to those comments into the database. Add this form to the sidebar in post.php, just after the searchform include:

<form action="<?=$_SERVER["PHP_SELF"]?>" method="post"> <input type="hidden" name="post_id" value="<?=$post_id ?>" />

<input type="hidden" name="posttitle" value="<?=$posttitle ?>" /> <h3>Add a comment</h3>

<?php

if (isset($message)) {

echo "<p class='message'>".$_POST["message"]."</p>";

313

B L O G D E S I G N S O L U T I O N S

}

?>

<p>Name: <input name="name" type="text" /></p> <p>Email: <input name="email" type="text" /></p> <p>Website: <input name="website" type="text" /></p>

<p>Comment: <textarea name="comment" cols="25" rows="15"> </textarea></p>

<p><input type="submit" name="postcomment" value="Post comment" /></p> </form>

Now add the following script to the end of the PHP code (just before the closing ?> delimiter) at the top of your document:

// If comment has been submitted and post exists then add comment to database

if (isset($_POST["postcomment"]) != "") {

$posttitle = addslashes(trim(strip_tags($_POST["posttitle"]))); $name = addslashes(trim(strip_tags($_POST["name"])));

$email = addslashes(trim(strip_tags($_POST["email"]))); $website = addslashes(trim(strip_tags($_POST["website"]))); $comment = addslashes(trim(strip_tags($_POST["comment"])));

$sql = "INSERT INTO comments (post_id,name,email,website,comment)

VALUES ('$post_id', '$name', '$email', '$website', '$comment')"; $result2 = mysql_query($sql);

if (!$result2) {

$message = "Failed to insert comment.";

}else {

$message = "Comment added."; $comment_id = mysql_insert_id();

// Send yourself an email when a comment is successfully added $emailsubject = "Comment added to: ".$posttitle;

$emailbody = "Comment on '".$posttitle."'"."\r\n"

."http://www.your-domain-name.com/post.php?post_id=".$post_id

."#c".$comment_id."\r\n\r\n"

.$comment."\r\n\r\n"

.$name." (".$website.")\r\n\r\n"; $emailbody = stripslashes($emailbody);

$emailheader = "From: ".$name." <".$email.">\r\n"."Reply-To: "

.$email;

mail("you@your-domain-name.com", $emailsubject, $emailbody, $emailheader);

314

W R I T E Y O U R O W N B L O G E N G I N E

// direct to post page to eliminate repeat posts header("Location: post.php?post_id=$post_id&message=$message");

}

}

This code inserts a new comment into the database and e-mails you when a new comment is added. Stepping through the code:

if (isset($_POST["postcomment"]) != "") {

If the Post comment button has been pressed, the comment can be added to the database.

$posttitle = addslashes(trim(strip_tags($_POST["posttitle"]))); $name = addslashes(trim(strip_tags($_POST["name"])));

$email = addslashes(trim(strip_tags($_POST["email"]))); $website = addslashes(trim(strip_tags($_POST["website"]))); $comment = addslashes(trim(strip_tags($_POST["comment"])));

The post title (sent as a hidden field), commenter’s name, e-mail address, website, and comment are all gathered from the query string and are tidied up by nesting three functions. Firstly strip_tags eliminates any HTML and PHP from the comment input, then

trim removes white space (such as spaces and line breaks) from either end of the input, 7 and finally addslashes ensures the text is formatted suitably for database entry.

$sql = "INSERT INTO comments (post_id,name,email,website,comment)

VALUES ('$post_id', '$name', '$email', '$website', '$comment')"; $result2 = mysql_query($sql);

if (!$result2) {

$message = "Failed to insert comment.";

}else {

$message = "Comment added.";

The database insert is performed. Note that the post_id is inserted with the comment so in future the blogging engine will know which comments go with which posts.

$comment_id = mysql_insert_id();

As when inserting a new post, the comment_id for a new comment is automatically generated by MySQL. The latest id can be retrieved using the mysql_insert_id function.

Now comes part of the script which e-mails yourself the comment so you know as soon as someone comments on your blog. PHP uses the mail function to send e-mail. An e-mail is made up of 4 four parts: the to address, the subject, the body, and the headers (which contain additional information such as the sender’s details and cc’d addresses). The mail function works like this:

mail(to address, subject, body, headers)

315