帮我删除mysql_insert_id

时间:2011-05-12 02:24:12

标签: php mysql

有三个表(博客,标签和博客标签),所有AI和ID都设置为主键。我正在建立一个标记系统来跟踪我的网站(localhost)。下面的代码有点工作,但是mysql_insert_id似乎不够可靠,因为我得到了一些重复的行,偶尔有0个值。

/// inserts the blog into blog table.
$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>";

/// let's see what tags we have and explode them.
//$tags  = $_POST['tags'] which is an array of words seperated by comma
$tags = 'fishing';
$pieces = explode(",", $tags);

/// go through the tags  and add to tags table if needed.
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>";
}

/// for each tag we have, let's insert the blogstags table so we can reference which blog goes to which tag.  Blogstags_id should map to the id of the blog.

$insert3 = mysql_query("INSERT INTO blogstags (id, tag_id, blogstags_id) VALUES ('','$taggit2','$taggit1')")or die( 'Error: ' . mysql_error());

}

猜猜我需要一个与mysql_insert_id不同的解决方案 - 想法?建议?

按要求的表格结构:

CREATE TABLE IF NOT EXISTS `blogs` (
  `id` int(11) NOT NULL auto_increment,
  `url` text NOT NULL,
  `user` text NOT NULL,
  `pass` text NOT NULL,
  `dname` text NOT NULL,
  `islocal` varchar(3) NOT NULL,
  `cat2post` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;


CREATE TABLE IF NOT EXISTS `blogstags` (
  `id` int(11) NOT NULL auto_increment,
  `tag_id` int(11) NOT NULL,
  `blogstags_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;


CREATE TABLE IF NOT EXISTS `tags` (
  `id` int(11) NOT NULL auto_increment,
  `tag` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

2 个答案:

答案 0 :(得分:1)

mysql_insert_id()工作正常。问题可能是您正在使用持久连接。通过持久连接,可以发生各种时髦的并发问题。除非你真的必须这样做,否则不要使用它们。

答案 1 :(得分:0)

两个选项 - 您可以切换到PostgreSQL,它允许您return一个auto_incremented ID作为插入查询的一部分。

或者,如果你坚持使用MySQL,你可以使用MySQL LAST_INSERT_ID()函数 -