mysql_insert_id()函数返回上一步INSERT操作产生的ID。

收集的当前这个数据库连接中发生的最后一次insert操作的结果,而AUTO_INCREMENT数据的唯一性

如果上一查询没有产生AUTO_INCREMENT的ID,则mysql_insert_id()返回0

mysql_insert_id不会出错,不过条件是必须有一个字段为auto_increment,而且类型为int。

参考:http://www.360doc.com/content/11/0524/16/987036_119061400.shtml

举例:

<?php

/*  数据库建表
CREATE TABLE `test` (
  `id` int(11) NOT NULL auto_increment,
  `type` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
*/

set_time_limit(0);

$type = intval($argv[1]);
$conn = mysql_connect("127.0.0.1", 'root', "123456") or die('Could not connect: ' . mysql_error());
mysql_select_db("test") or die('Could not select database');
mysql_query("set names 'utf8'"); 


while(1){
	if(file_exists("stop"))
		exit;
	mysql_query("insert into test (`type`) values({$type}) ");
	$lastId = mysql_insert_id();
	$rs = mysql_query("select * from test where id = {$lastId}");
	$v = mysql_fetch_array($rs);
	echo $v['id']."    ".$v['type']."\n";
	sleep("1");

}

mysql_close($conn);

?>

同时开php-ftest.php1

php-ftest.php2

php-ftest.php3

会发现没有冲突