数据库插入循环执行次数超过应有的次数


Database Insert in loop executing more times than it should

好吧,这是一些较旧的代码,但它插入的比应有的更多。在我清理它之前,我试图理解为什么。 现在 $_POST[标签] 只有 1 个值。 我正在爆炸它并循环播放。 但是底部的 insert3 语句插入以零作为值的行。

我不知为什么。

if($_POST['sec'] == "next") {
      $bloguser = $_POST['bloguser'];
      $blogpassword = $_POST['blogpassword'];
      $blog = $_POST['blog'];
mysql_select_db($database) or die ("Unable to select database!"); 
$insert = mysql_query("INSERT INTO blogs (id, url, user, pass, dname, islocal, cat2post) VALUES ('', '$blog', '$bloguser', '$blogpassword', '','NO','$_POST[cat2blog]')")or die( 'Error: ' . mysql_error());
$taggit1 = mysql_insert_id();
$page->content .= "<p class='"alert'">Success - External blog Added!</p>";

$tags  = $_POST['tags'];
$pieces = explode(",", $tags);
foreach ($pieces as $l){
$l = trim($l);  
$query = "SELECT id FROM tags WHERE tag = '$l'";
$result = mysql_query($query) or die( "Error: " . mysql_error() . " in query $query");
$row = mysql_fetch_array($result);
$taggit2 = $row[0];
if ($taggit2 == '') {
$insert2 = mysql_query("INSERT INTO tags (id, tag) VALUES ('','$l')")or die( 'Error: ' . mysql_error());
$taggit2 = mysql_insert_id();
$page->content .= "<p class='"alert'">This tag didn't exist - so I inserted a new tag</p>";
}

$insert3 = mysql_query("INSERT INTO blogstags (id, tag_id, blogstags_id) VALUES ('','$taggit2','$taggit1')")or die( 'Error: ' . mysql_error());
$page->content .= "<p>Inserted one    </p>";
}

/// some page content crap that doesn't matter to the problem goes here///
}

像这样输入 - 第二条记录是正确的。 第一个不应该插入——

id    tag_id   blogstags_id
1      1           0
2      1           6

我认为问题是我在哪里爆炸

$tags  = $_POST['tags'];
$pieces = explode(",", $tags);
foreach ($pieces as $l){
$l = trim($l); 

但是 POST 值只是一个单词,那么为什么它会在循环中运行两次呢?

如果$_POST['tags'];不包含,,那么$pieces = explode(",", $tags);将是一个只有一个元素的数组。

我建议print_r($pieces);进行理智检查,这是真的。