I had table like this:
post:
+----------------+-----------+
| article_id | tags |
+----------------+-----------+
| 1 | x1,x2,x3|
| 2 | x1,x4,x5 |
+----------------+-----------+
what i am trying to do is to normalize it, so i create 2 more tables:
tags:
+----------------+-----------+
| tag_id | tag_name |
+----------------+-----------+
| 1 | x1 |
| 2 | x2 |
| 3 | x3 |
+----------------+-----------+
post_tag:
+----------------+-----------+
| id_post | id_tag |
+----------------+-----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
+----------------+-----------+
I have exported all tags from post table to tags table and now each tag has his own id in tags table, but I am so confused when i am thinking how to do it with post_tag table?
edit: questin is how to populate post_tag table, how the query would look like?
tried like this
$sql=mysql_query("SELECT * FROM post");
while($row=mysql_fetch_array($sql)) {
$article_id=$row['article_id'];
$all_tags =$row['tags'];
$tags= explode(",",$all_tags);
foreach($all_tags as $tag) {
$sql2=mysql_query("SELECT * FROM tags WHERE tag_name = '$tag'");
while($row=mysql_fetch_array($sql2)) { $tag_id=$row['tag_id']; $q = "INSERT INTO post_tag (id_post, id_tag) VALUE ('$article_id', $tag_id')";
$r = mysql_query($q);
}
}
}
but it doesn’t write complete post_tag table
Maybe this one will work?
After running the loop, you will need to drop the old column in
posttable