最近和sobin在做一个精品课程的项目,因为用到一个固定的id作为表间关联,所以在前一个表插入数据后要把插入数据生成的自增id传递给下一个表。研究了一番决定使用mysql提供了一个last_insert_id()的函数。 liehuo.net last_insert_id() (with no argument) r
最近和sobin在做一个精品课程的项目,因为用到一个固定的id作为表间关联,所以在前一个表插入数据后要把插入数据生成的自增id传递给下一个表。研究了一番决定使用mysql提供了一个last_insert_id()的函数。 liehuo.net
last_insert_id() (with no argument) returns the first automatically generated value that was set for an auto_increment column by the most recently executed insert or update statement to affect such a column. for example, after inserting a row that generates an auto_increment value, you can get the value like this:
copy to clipboard
mysql> select last_insert_id();
-> 195
简单说来,,就是这个函数将返回插入的那条记录在表中自增的那个字段的值,一般我们都给那个自增字段命名为id。这样就可以返回刚插入的记录的id值了。 liehuo.net
一个简单的例子:
copy to clipboard
$query="insert into `testtable` (`clou1`,`clou2`) values ('testvalue','test')";
mysql_query($query);
$query="select last_insert_id()";
$result=mysql_query($query);
$rows=mysql_fetch_row($result);
echo $rows[0];
这个函数是基于connection的,也就是不会被其他客户端的connection影响到,所以结果是准确的。如果使用select max(id) from table,在高密度的插入请求下,是有可能出问题的,返回错误值
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!