Linked Questions

Popular Questions

Insert foreach ID to other tables

Asked by At

I've tried looking for what I want, but I'm still confused about the code. my problem is like this:

I have 3 tables

 1. table1 (post id, field2, ...) ex. (1, ...)
 2. table2 (tag id, tag) ex. ("1, ...", "2, ...")
 3. table3 (post id, tag id) ex. ("1, 1", "1, 2")

so how do I enter values post id & tag id into table3?

PHP Code:

  foreach($tags as $tag){
    $query_insert_tags = mysql_query("INSERT INTO tb_tags (tag) VALUES ('$tag')") or die(mysql_error());
    $query_insert_tag_posts = mysql_query("...") or die(mysql_error());
  }

like this:

insert into table3 (post id, tag id) 
select post id from table1 and select tag id from table2

Don't know if it's true like this, and i dont know too how to put the value into the database

INSERT INTO table3 (post_id, tag_id)
SELECT table1.postid, table2.tagid FROM table3
JOIN table1 ON table3.postid = table1.postid
JOIN table2 ON table3.tagid = table2.tagid

Related Questions