开发者

Database Insert in loop executing more times than it should

开发者 https://www.devze.com 2023-03-05 01:10 出处:网络
O.K. this is some older code, but it\'s inserting more than it should. Before I clean it up I\'m trying to understand why.Right now $_POST[tags] has only 1 value.I\'m exploding it and looping through.

O.K. this is some older code, but it's inserting more than it should. Before I clean it up I'm trying to understand why. Right now $_POST[tags] has only 1 value. I'm exploding it and looping through. BUT the insert3 statement towards the bottom is inserting rows with zero's as the value.

I'm at a loss for why.

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///

}

Entering like this - the second record is correct. And the first just shouldn't be inserted -

id    tag_id   blogstags_id
1      1           0
2      1           6

I think the problem is where i'm exploding

$tags  = $_POST['tags'];
$pieces = explode(",", $开发者_开发问答tags);
foreach ($pieces as $l){
$l = trim($l); 

But the POST value is just a single word, so why would it run through the loop twice?


If $_POST['tags']; doesn't contain a ,, then $pieces = explode(",", $tags); will be an array with only one element.

I suggest doing print_r($pieces); to sanity check that's true.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号