Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Artur Lipiński Avatar asked May 20 '26 11:05

Artur Lipiński


1 Answers

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);
}
like image 97
Ergec Avatar answered May 22 '26 01:05

Ergec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!