|
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 -f test.php 1
php -f test.php 2
php -f test.php 3
会发现没有冲突 |
|
|