一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

PHP中mysql_insert_id()函数获取最后插入记录ID编号

时间:2015-01-08 编辑:简简单单 来源:一聚教程网

这个问题以前绝壁遇到过,太久没写不记得(貌似当时是CI框架直接有相关函数的),然后这次又遇到了,再次滚去查了一下,这里说的并非是PDO之类的情况,而是用过时的连接和执行方式之后怎么进行操作。

有什么SQL语句实现的,但明显不合适,当收到多人操作时,顿时就混乱不堪。

所以在此,用mysql_insert_id()函数搞定,他会返回AUTO_INCRESEMENT的值。

 代码如下 复制代码

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
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()

热门栏目