自定义CMS如何使用PHP / MySQL数据库为帖子创建类别

时间:2014-06-21 15:58:24

标签: php mysql database categories

我正在互联网上搜索,但我似乎无法找到一个简单的教程,可以帮助我建立我的自定义CMS。

我想在帖子中添加多个类别。

例如:

Title: post 1 
Content: content goes here 
Categories: Technology, Computers, Science, Internet

Title: post 2 
Content: content goes here 
Categories: Music, Jazz, Classic

所以这就是我要发表文章的内容

我的数据库结构

postID | postTitle | postDesc | postCont | postDate


1   Post 1      info1   content1    date1
2   Post 2      info2   content2    date2
3   Post 3      info2   content3    date3

表格

<form action='' method='post'>

<p><label>Title</label><br />
<input type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'></p>

<p><label>Description</label><br />
<textarea name='postDesc' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postDesc'];}?></textarea></p>

<p><label>Content</label><br />
<textarea name='postCont' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postCont'];}?></textarea></p>

<p><input type='submit' name='submit' value='Submit'></p>

</form>

将其放入数据库的PHP代码

//insert into database
$stmt = $db->prepare('INSERT INTO blog_posts (postTitle,postDesc,postCont,postDate) VALUES (:postImage, :postTitle, :postDesc, :postCont, :postDate)') ;
$stmt->execute(array(
':postTitle' => $postTitle,
':postDesc' => $postDesc,
':postCont' => $postCont,
':postDate' => date('Y-m-d H:i:s')
));

//redirect to index page
header('Location: index.php?action=added');
exit;

1 个答案:

答案 0 :(得分:5)

以下是适用于此任务的多对多关系的基本原则示例。当一个表中的一个或多个行可能与另一个表中的多个行相关联时,多对多关系是两个表之间的设计模式。两个表之间的关系存储在第三个表中,该表存储每个关系的主键(postIDcategoryID列)。

数据库表的示例:

post

postID | postTitle | postDesc | postCont | postDate

1    Post 1    info1    content1    date1
2    Post 2    info2    content2    date2
3    Post 3    info2    content3    date3

post_category

postID | categoryID

1    1
2    5
3    1
2    6
3    3
2    7
1    2
1    3
1    4

category

categoryID | categoryTitle

1    Technology
2    Computers
3    Science
4    Internet
5    Music
6    Jazz
7    Classic

MySQL查询示例:

MySQL query to get all categories related to post

SELECT * FROM `category` NATURAL JOIN `post_category` WHERE postID=1

categoryID | categoryTitle | postID 

1    Technology    1
2    Computers     1
3    Science       1
4    Internet      1

MySQL query for all posts of the category

SELECT * FROM `post` NATURAL JOIN `post_category` WHERE categoryID=1

postID | postTitle | postDesc | postCont | postDate | categoryID 

1    Post 1    info1    content1    date1    1
3    Post 3    info2    content3    date3    1