如何在php和sql中将标签插入3个表系统

时间:2011-11-28 12:26:10

标签: php mysql insert tags

我正在尝试制作3个表标签系统。我在mysql中有3个表:

#Articles#
id
article
content

#Tags#
tag_id
tag (unique)

#tagmap#
id
tag-id
articleid

在我提交的php中,我有:

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

for ($x = 0; $x < count($tags); $x++) {
    //Add new tag if not exist
    $queryt = "INSERT INTO `tags` (`tag_id`, `tag`) VALUES ('', '$tags[x]')";
    $maket = mysql_query($queryt);

    //Add the relational Link, now this is not working, beacasue this is only draft
    $querytm = "INSERT INTO `tagmap` (`id`, `tagid`, `articleid`) VALUES ('',  (SELECT `tag_id` FROM `tags` WHERE tag_id  = "$tags[x]"), '$articleid')";
    $maketm = mysql_query($querytm);
    }

当我向文章提交新标签时,这不起作用。 Mysql不在我的Tags表中创建新标签。

PS。抱歉英文不好。

1 个答案:

答案 0 :(得分:3)

你错过了'x'变量的$符号。尝试这两行。

'" . $tags[$x] . "'

我也建议这样做,不需要使SQL查询复杂化。

$tags= explode(',', strtolower($_POST['insert_tags']));
for ($x = 0; $x < count($tags); $x++) {
    //Add new tag if not exist
    $queryt = "INSERT INTO `tags` (`tag_id`, `tag`) VALUES ('', '" . $tags[$x] . "')";
    $maket = mysql_query($queryt);

    //Get tag id
    $tag_id = mysql_insert_id();

    //Add the relational Link, now this is not working, beacasue this is only draft
    $querytm = "INSERT INTO `tagmap` (`id`, `tagid`, `articleid`) VALUES ('',  '$tag_id', '$articleid')";
    $maketm = mysql_query($querytm);
}