Artur Lipiński
Artur Lipiński

Reputation: 69

How to insert tags into 3 table system in php and sql

I am trying to make 3 table tags system. I have 3 table in mysql:

#Articles#
id
article
content

#Tags#
tag_id
tag (unique)

#tagmap#
id
tag-id
articleid

In my submit php I have:

$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);
    }

This is not working when I submit new tags to article. Mysql not create new tags in my Tags table.

PS. Sorry for bad english.

Upvotes: 3

Views: 1316

Answers (1)

Ergec
Ergec

Reputation: 11834

You are missing $ sign for 'x' variable. Try like this for both lines.

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

Also I suggest this way, no need to complicate your SQL queries.

$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);
}

Upvotes: 3

Related Questions