<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
// A MySQLi connection
/* Database setup:
`posts`
`id`
`text`
`tags`
`tag`
`post_id`
*/
function add_post ($text, $tags = array()) {
global $sql;
$sql->query('INSERT INTO `posts` (`text`) VALUES ("'.$sql->real_escape_string($text).'");');
// Insert the post into the posts table
$postID = $sql->insert_id;
// Capture its id
if (count($tags) != 0) {
foreach ($tags as &$tag) {
$tag = $sql->real_escape_string($tag);
}
unset($tag);
// Escape every tag
$sql->query('INSERT INTO `tags` (`tag`, `post_id`) VALUES ("'.implode('", '.$postID.'), ("', $tags).'", '.$postID.');');
// Insert the tags associated with this post as records in the tags table
}
}
// If/when you write update_post and delete_post functions, you will need to manage the tags associated with them as well
// Probably it's best to use a relational system like InnoDB
function get_top_tags ($num = 3) {
global $sql;
$result = $sql->query('SELECT `tag`, COUNT(`tag`) AS `frequency` FROM `tags` GROUP BY `tag` ORDER BY `frequency` DESC LIMIT '.(int) $num.';');
// Get the tags in order of most to least frequent, limited to $num
$tags = array();
while ($row = $result->fetch_assoc()) {
$tags[] = $row['tag'];
}
// Turn them into an array
return $tags;
}
// Example usage:
add_post('This is a new post.', array ('this', 'post', 'new'));
add_post('This is an old post.', array ('this', 'post'));
add_post('That is a medium-aged post.', array ('post'));
?>
<h1>Top Tags</h1>
<ol>
<?php
foreach (get_top_tags(3) as $tag) {
?>
<li><?php echo $tag; ?></li>
<?php
}
?>
</ol>
<!-- Should print
1. post
2. this
3. new
-->
讓我知道你是否需要幫助。未經測試的代碼,所以不知道它是否有效。
什麼不在你的代碼中工作? – user20232359723568423357842364
你不需要像這樣的設置。你應該有這樣的設置:'posts(id,text)','tags(id,tag)'和'relationships(id,post_id,tag_id)''。然後,您可以通過'tag_id DESC'對'關係'表進行排序,並拉動最常用的3個。 –
當沒有信息存儲但不需要代理主鍵時,沒有理由使用「標籤」表。 「關係」表也不需要「id」列; 'post_id,tag'本身就是主鍵。看起來你已經養成了爲每個表添加「id」列的習慣,即使它不需要。 –