php - 标签系统,检查标签是否已经存在
问题描述
我正在使用 PhP 和 MySQL (InnoDB) 开发标签系统。在我的数据库中,我有 2 个表:
contentTable
:
content
|tagsID
“内容1” | “1、3”
“内容2” | “2、3”
tags
:
tagID
(主键) |tag
1 | “政治”
2 | “面试”
3 | “经济”
每个内容都有一组标签,每个标签 ID 在 tagsID 中列出。
我正在尝试让 insert.php 添加新内容。在添加内容之前,会检查每个标签以确保它存在:
- 如果没有,它会将其添加到标签表并获取他的主键(
tagID
) - 如果它已经存在,它会得到他的
tagID
.
tagsID[] 在每次迭代中填充每个标签的 ID,然后连接起来('$tagID1 .', ' . $tagID2 etc..')存储tagsID
在contentTable
.
我认为我编写的代码是:效率低下、设计糟糕、效率低下。
$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[])
}
你会如何处理这个?
解决方案
推荐阅读
- c# - 当实例化一个 Prefab 的多个 GameObjects 时,只有最后一个创建的按钮起作用
- c# - 我有一个统一项目,我在其中使用颜色,但我需要一些帮助
- javascript - 强制刷新和清除缓存 - ReactJS
- python - pycharm 编码错误信息。numpy.ndarray
- angular - 仅针对一个用户的随机 CORS 预检问题
- javascript - NextJS | getStaticProps 在构建时失败
- websocket - 三星电视复制权限 Websocket
- android - 初始化提供程序时 Firebase 身份验证崩溃(Android)
- c# - 如何强制 Odata 使用我的自定义 DTO 对象?
- mysql - Rails has_many 基于 json 数组列