简体   繁体   English

从mysql数据库中获取自动增量ID

[英]Fetch the auto increment id from mysql database

I have a database with an Auto increment field. 我有一个带有自动递增字段的数据库。 I want to retrieve the value of the Auto increment column whenever i insert a record in database. 每当我在数据库中插入一条记录时,我都想检索“自动增量”列的值。 I am using mysql as my database and PHP as my programming language. 我使用mysql作为数据库,使用PHP作为编程语言。 I tried using mysql_insert_id() function but then it is not suitable when there are large number of insertion taking place at same point of time. 我尝试使用mysql_insert_id()函数,但是当在同一时间点发生大量插入时,它不合适。

I want to retrieve the value of AI column because i am storing a file for respective record and since i am storing the files in a single directory i need the file name to be unique. 我想检索AI列的值,因为我正在为各个记录存储文件,并且由于我将文件存储在单个目录中,因此我需要文件名是唯一的。 Any other way to do the same thing? 还有其他方法可以做同样的事情吗?

It should be safe for you to use mysql_insert_id(), because it will return the last inserted AI value of the current connection (see php.net ). 使用mysql_insert_id()应该是安全的,因为它将返回当前连接的最后插入的AI值(请参阅php.net )。 So as long as you call the method right after the INSERT query in your script, there won't be any race conditions, even if your script is running concurrently multiple times. 因此,只要您在脚本中的INSERT查询之后立即调用该方法,就不会有任何竞争条件,即使您的脚本并发运行多次。

for a single insert you can do this in a single statementto ensure you get the right value 对于单个插入,您可以在单个语句中执行此操作,以确保获得正确的值

Pseudo code: 伪代码:

$query = "INSERT INTO TABLE1 VALUES(null, 'test')";
$id = mysql_execute("$query; SELECT LAST_INSERT_ID();"

Another way could be to manuelly set ids. 另一种方法是手动设置id。

let's say you want to add 1000 rows 假设您要添加1000行

1. query current ai value and store value

2. alter table set ai value = current + 1000;

3. make your inserts with setting ai value manually

   INSERT INTO TABLE1 VALUES ($id, 'test$id');

Use uniqid() for the filename. 使用uniqid()作为文件名。 "Gets a prefixed unique identifier based on the current time in microseconds." “基于当前时间(以微秒为单位)获得带前缀的唯一标识符。”

Have a look here php.net/manual/en/function.uniqid.php 在这里看看php.net/manual/en/function.uniqid.php

you can also generate a unique number using uniqid(), insert it in the table and use the same for file name. 您还可以使用uniqid()生成唯一编号,将其插入表中,并将其用作文件名。

http://php.net/manual/en/function.uniqid.php http://php.net/manual/zh/function.uniqid.php

使用SQL检索最后一次插入的ID的另一种方法:

SELECT id FROM table ORDER BY id DESC LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM