对于获得最后插入数据的记录ID号我们通常会用到mysql_insert_id()或select max(id)来操作了,下面一起来看看小编对于这两个函数的一些理解.
这个问题以前绝壁遇到过,太久没写不记得(貌似当时是CI框架直接有相关函数的),然后这次又遇到了,再次滚去查了一下,这里说的并非是PDO之类的情况,而是用过时的连接和执行方式之后怎么进行操作.
有什么SQL语句实现的,但明显不合适,当收到多人操作时,顿时就混乱不堪,所以在此,用mysql_insert_id()函数搞定,他会返回AUTO_INCRESEMENT的值,代码如下:
- <?php
- $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
- if (!$link) {
- die('Could not connect: ' . mysql_error());
- } //开源软件:Vevb.com
- mysql_select_db('mydb');
- mysql_query("INSERT INTO mytable (product) values ('kossu')");
- printf("Last inserted record has id %d ", mysql_insert_id());
- ?>
刚开始我还在想这个函数不会遇到相同的问题么,然后小新告诉我是基于当前数据库连接的,顿时不怕不怕啦.
当然还有如下代码:
mysql_query("select max(id) from t1",$link);
当然,现在这种连接方式已经out的可以了.
这里也有说明:
- Warning
- This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
- mysqli_insert_id()
- PDO::lastInsertId()
新闻热点
疑难解答