获得了三个表(博客、标签和博客标签),所有的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的解决方案- ideas?有什么建议吗?
根据请求的表结构:
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 ;发布于 2011-05-12 13:54:03
mysql_insert_id()运行得很好。问题可能是您正在使用持久连接。有了持久的连接,各种时髦的并发问题都可能发生。不要使用它们,除非你真的,真的需要。
发布于 2011-05-12 10:43:45
有两个选项--您可以切换到PostgreSQL,它允许您将一个auto_incremented ID作为插入查询的一部分。
或者,如果您坚持使用MySQL,则可以使用MySQL LAST_INSERT_ID()函数-
https://stackoverflow.com/questions/5972686
复制相似问题