php - Inserting data into 3 tables in 1 query -
basically have site tag-it system similar 1 on site, table structures follows
topics topic_tags tags topic_id tag_id tag_id topic_data topic_id tags
now trying run series of queries when topic posted, enters relevant topic data topic table(currently working), puts tags tags table(currently working), puts tag_id tags table topic_tags table in rows linked topic_ids(not working currently)
right it's not entering tag_ids topic_tags tags table, it's entering last tags info row , not storing associated topic_ids
here code
$tags = isset($_post['tags']) ? $_post['tags'] : null; if (is_array($tags)) { foreach ($tags $t) { // checking duplicate $sql_d = "select * tags tags='$t'"; $res=mysql_query($sql_d); $res = mysql_num_rows($res); if($res<1) { // escape $t before inserting in db $sql = "insert tags (tags) values('$t')"; mysql_query($sql); } } } else { echo 'invalid tag'; } $tag_id = isset($_post['tag_id']) ? $_post['tag_id'] : null; if (is_array($tag_id)) { foreach ($tag_id $tid) { // escape $t before inserting in db $sql = "insert topic_tags (tag_id) values('$tid')"; mysql_query($sql); } } $sql="insert topic_tags (tag_id)values(last_insert_id())"; $result=mysql_query($sql); $topic_data= htmlentities($_post['topic_data']); $posted_by = $_session['user_id']; $posted = "date_add(now(),interval 2 hour)"; $invisipost = isset($_post['invisipost']) ? $_post['invisipost'] : 0 ; if (($topic_data=="")) echo "<h2>opps...</h2><p>you did not fill out required fields.</p>"; else $sql="insert topics(topic_data, posted_by, posted, invisipost)values('$topic_data', '$posted_by', $posted, $invisipost)"; $result=mysql_query($sql); if($result){ $sql="insert topic_tags (topic_id)values(last_insert_id()) topic_tags.tag_id='". $_get['tags'] ."'"; $result=mysql_query($sql);
edit
would better add topics data first, tags, topic_tags info??
i think should insert topic_tags
in 1 step in 'foreach' loop. last query
$sql="insert topic_tags (topic_id)values(last_insert_id()) topic_tags.tag_id='". $_get['tags'] ."'"
is neither insert nor update , wrong
(edit) need in lines of below:
foreach ($tag_id $tid) { // escape $t before inserting in db $sql = "insert topic_tags (topic_id,tag_id) values($topic_id,$tid)"; mysql_query($sql); }
Comments
Post a Comment