Question

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. 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.

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. Any other way to do the same thing?

Was it helpful?

Solution

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). 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.

OTHER TIPS

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.

let's say you want to add 1000 rows

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. "Gets a prefixed unique identifier based on the current time in microseconds."

Have a look here 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.

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

An alternative way to retrieve the ID of the last insert using SQL:

SELECT id FROM table ORDER BY id DESC LIMIT 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top