2015-08-22 211 views
-1

我目前在PHP中创建博客,目前博客只能接受每个帖子的单个标签或标签。PHP中的多个标签或标签

请给我一个关于如何在PHP中为每个帖子创建或添加多个标签或标签的想法。我希望帖子有多个标签或标签。

谢谢

+0

简单,例如使用一个表格:ID这样blog_post_id标签可以为一个帖子保留多个标签 – jewelhuq

+3

标记为太宽泛。 http://stackoverflow.com/tour – DeDee

+0

认为多对多的关系。通过链接表 – nomistic

回答

0

您使用的数据库类型非常重要。例如,对于像MongoDB这样的事情来说,这样做会容易得多,但为了交叉兼容性,这是一个简单的平坦方法。

选项1: 这里是一个快速入侵,每个人都会倒下,但我很好。

<?php 
    $tags = "tag1,tag2,tag3"; 

    $exploded_tags = explode(",", $tags); 

    foreach($exploded_tags as $elem) { 
     echo $elem; 
    } 

将它们存储为以逗号分隔的标记,并且当您为标记查询数据库时,将它们分解。

选项2:

你的“博客​​文章”必须以某种方式对数据库的标识,通过标题为“我 - 博客 - 后”之称。所以你会有一个名为“blog_posts”的表,另一个名为“tags”。在“标签”中,您将有一个名为“post_title”的列。让我们说你是通过你的网址中的文章的标题,你可以使用去抓住那个标题:

<?php 
    $post_title = $_GET['post']; // my-blog-post 
    $post_tags = array("tag1","tag2","tag3"); 

    function insert_tags($title, $tags) { 
    $query = $database->prepare("INSERT INTO `tags` (`post_title`, `tags`) VALUES(?,?)"); // this Query inserts the post title for each tag to identify 

    $query->bindValue(1, $title); // injects the title to the column post_title 
    $query->bindValue(2, $tags); // injects the tag to the column tags 

    try { 
    $query->execute(); // executes the above query 
    } catch (PDOException $e) { 
    echo $e->getMessage(); 
    } 

    return 0; // please don't do parenthesis 
    } 

    foreach($post_tags as $elems) { 
    // since the tags are in an array, we need to loop through them 
    insert_tags($post_title, $elems); 
    // this function will now insert each individual tag with the title "my-blog-post" 
    } 

有PDO的代码,所以如果你不使用PDO它仍然是适应mysqli什么的。现在,一旦你在你的代码进入,你可以像这样的东西回忆起来:

<?php 
    function find_tags($post_title) { 
    $query = $database->prepare("SELECT * FROM `tags` WHERE `post_title` = ?' "); 

    $query->bindValue(1, $post_title); 

    $query->execute(); // getting rid of exceptions for ease. This will execute the query 

    return $query->fetchAll(); // Because we are fetching 2 if not more rows, we need to tell PDO to fetch everything it found and return it to the function that called it 

    } 

    $tags = find_tags($_GET['post_title']); //my-post-title 

    foreach($tags as $elems) { 
    echo $elems; 
    } 

此,在大多数情况下,应该工作。 Foreach可能有点矫枉过正,但这是总体思路。让我知道你是否需要解释

+0

非常感谢你提供的这个选项,我一定会试试这个,一旦得到结果就回来。再次感谢您 –

+0

它的工作!有效!有效!有效!有效!有效!有效! 选项1做到了一切! :D 非常感谢代码,我也能够在每个标签上添加链接。非常感谢,案件关闭。 :) –