首页 > 解决方案 > 标签系统,检查标签是否已经存在

问题描述

我正在使用 PhP 和 MySQL (InnoDB) 开发标签系统。在我的数据库中,我有 2 个表:

contentTable

content|tagsID

“内容1” | “1、3”

“内容2” | “2、3”

tags

tagID(主键) |tag

1 | “政治”

2 | “面试”

3 | “经济”

每个内容都有一组标签,每个标签 ID 在 tagsID 中列出。

我正在尝试让 insert.php 添加新内容。在添加内容之前,会检查每个标签以确保它存在:

tagsID[] 在每次迭代中填充每个标签的 ID,然后连接起来('$tagID1 .', ' . $tagID2 etc..')存储tagsIDcontentTable.

我认为我编写的代码是:效率低下、设计糟糕、效率低下。

        $tags = $_POST['tags'];
        $tags = explode(", ", $tags);

        foreach ($tags as $i => $tag ) {
            $req = $bdd-> prepare("SELECT tagID FROM tags WHERE tag = ?");
            $req->execute(array($tag));

            while ($tagID = $req->fetch())
            {
                if (empty($tagID['tagID'])) {
                    // create the tag (INSERT VALUES("", $tag))
                    // get the ID of the new tag
                    // add it to $tagsID[]
                    echo $tag . ' tag added, ID : ' . $newTagID . '<br>';
                } else {
                    // $tagID['tagID'] is added to $tagsID[]
                }
            }
            // JOIN string of $tagsID array in this format tagsID[0] . ", " . tagsID[1] . ", " etc...
            INSERT VALUES ($content, $tagsID[])
        }

你会如何处理这个?

标签: phpmysqlsqltags

解决方案


推荐阅读