所以我有3个表如下。
TOPICS TOPIC_TAGS Tags
topic_id tag_id tag_id
topic_data topic_id tags
现在我可以成功地将 topic_data 插入到 TOPICS 中,并且标签正在像这样插入......
tag_id tags
1 this
2 is
3 a
4 test
但是当我试图将 tag_ids 插入 TOPIC_TAGS 表时,它只是像这样插入最后一个
topic_id tag_id
0 4
并且在插入主题时也没有插入 topic_id。
这是发布数据的表单。
<form method="post" action="add_topic.php">
<table>
<tr>
<td align="left"><b>Enter your Topic keywords.
<ul id="topic" name="tags[]"></ul>
</td>
</tr>
<tr>
<td colspan="3"><textarea name="topic_data" cols="50" rows="3" id="topic_data" placeholder="What Topic are you talking about?"></textarea></td>
</tr>
<tr>
<td colspan="3" align="right">Invisipost: <input type="hidden" name="invisipost" value="0"><input type="checkbox" name="invisipost" value="1"> <input type="submit" name="Submit" value="Talk" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</form>
这是我的代码:
$tags = isset($_POST['tags']) ? $_POST['tags'] : null;
if (is_array($tags)) {
foreach ($tags as $t) {
// Checking duplicate
$sql_d = "SELECT * from tags where tags='$t'";
$res=mysql_query($sql_d);
$res = mysql_num_rows($res);
if($res<1)
{
// escape the $t before inserting in DB
$sql = "INSERT INTO tags (tags) VALUES('$t')";
mysql_query($sql);
}
}
} else {
echo 'Invalid tag';
}
$sql_s = "SELECT * from tags where tag_id='$tags'";
$tag_id = isset($_GET['tag_id']) ? $_GET['tag_id'] : null;
if (is_array($tag_id)) {
foreach ($tag_id as $tid) {
// escape the $t before inserting in DB
$sql = "INSERT INTO topic_tags (tag_id) VALUES('$tid')";
mysql_query($sql);
}
}
$sql="INSERT INTO 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 all the required fields.</p>";
else
$sql="INSERT INTO topics(topic_data, posted_by, posted, invisipost)VALUES('$topic_data', '$posted_by', $posted, $invisipost)";
$result=mysql_query($sql);
if($result){
$sql="INSERT INTO topic_tags (topic_id)VALUES(LAST_INSERT_ID()) WHERE topic_tags.tag_id='". $_GET['tags'] ."'";
$result=mysql_query($sql);