第一步:数据库的创建
1.使用phpmyadmian创建一个数据库,名字可以自己选,因为是博客有可能需要输入中文,所以MySQL连接校对选择:uft8_unicode_ci(或utf8_general_ci)
2.创建数据表
需要建立的数据表如图:
以创建blog_posts为例:
需要注意的是,blog_post_tags这张表无需设置主键。
第二步:使用PHP创建对象
创建blogpost.php文件,文件内容为:
以下是代码片段: <?php class BlogPost { public $id; public $title; public $post; public $author; public $tags; public $datePosted; //构造函数 function __construct($inId=NULL,$inTitle=NULL,$inPost=NULL,$inPostFull=NULL,$inAuthorId=NULL,$inDatePosted=NULL) { if (!empty($inId)) { $this->id = $inId; } if (!empty($inTitle)) { $this->title = $inTitle; } if (!empty($inPost)) { $this->post =$inPost; } if (!empty($inDatePosted)) { //将2005-05-03格式化为2005/05/03 $splitDate =explode("-",$inDatePosted); $this->datePosted = $splitDate[0]."/".$splitDate[1]."/".$splitDate[2]; } if (!empty($inAuthorId)) { //获取全名 $query = mysql_query("SELECT first_name, last_name FROM people WHERE id = ".$inAuthorId); $row = mysql_fetch_assoc($query); $this->author = $row["first_name"] ." " . $row["last_name"]; } $postTags = "No Tags"; if (!empty($inId)) { //获取文章标签 $query = mysql_query("SELECT tags.* From blog_post_tags LEFT JOIN(tags) ON (blog_post_tags.tag_id =tags.id) WHERE blog_post_tags.blog_post_id= ".$inId); $tagArray = array(); $tagIDArray = array(); while ($row = mysql_fetch_assoc($query)) { array_push($tagArray,$row["name"]); array_push($tagIDArray,$row["id"]); } if (sizeof($tagArray)>0) { foreach ($tagArray as $tag) { if ($postTags == "No Tags") { $postTags = $tag; } else { $postTags = $postTags.",".$tag; } } } } $this->tags = $postTags; } } ?>
第三步:从MySQL获取数据,并显示内容
1.创建includes.php
以下是代码片段: <?php include ’blogpost.php’; $connection = mysql_connect("localhost","root","") or die("
Sorry, we ware unable to connect to the datebase server.
"); $query = mysql_query("SET NAMES ’utf8’"); //如果需要显示中文,则必须要在数据库连接后面加上此句 $database = "myblog"; mysql_select_db($database,$connection) or die("Sorry, We were unable to connect the datebase.
"); function GetBlogPosts($inId=NULL,$inTagId=NULL) { if (!empty($inId)) { $query = mysql_query("SELECT * FROM blog_posts WHERE id=".$inId."ORDER BY id DESC"); } elseif (!empty($inTagId)) { $query = mysql_query("SELECT blog_posts.* FROM blog_post_tags LEFT JOIN (blog_posts) ON (blog_post_tags.postID = blog_posts.id) WHERE blog_post_tags.tagID.".$tagID."ORDER BY blog_posts.id DESC"); } else { $query = mysql_query("SELECT * FROM blog_posts ORDER BY id DESC"); } $postArray = array(); while ($row = mysql_fetch_assoc($query)) { $myPost = new BlogPost($row["id"],$row["title"],$row["post"],$row["postfull"],$row["author_id"],$row["date_posted"]); array_push($postArray,$myPost); } return $postArray; } ?>2.创建实例index.php
以下是代码片段:
My Simple Blog
".$post->title."
"; echo "".$post->post."
"; echo " Posted By: " . $post->author . " Posted On: " . $post->datePosted . " Tags: " . $post->tags . ""; echo "