![]() |
Last Inserted ID?
Hey,
I've been trying for a while to get the last inserted id of a table to use in my next query, the problem is mysql_insert_id seens to produce an empty return, any ideas? Thanks :-) |
Does the table you are inserting into contain a primary, auto increment index?
|
Indeed it does :-) although not in correlation to the other table.
|
You'll have to paste me your
INSERT statement so that I can see. |
Theres 4, but, i'm trying to do it with PHP if that's possible? It's just a standard insert query (forums based).
|
Well, it's going to get the ID from the very last query, regardless of whether or not it's an
INSERT or not. Do you happen to have another query in between the INSERT you want the ID from, and the mysql_insert_id call? |
Hey Winsrev,
A simple example might show you where you might have done things wrong. PHP Code:
Good luck, DragonBe |
It's order is:
First Query mysql_insert_id(); Second Query Third Query mysql_insert_id(); Fourth Query Problem is the second mysql_insert_id produces nothing although the first one works. |
Is the third query not an
INSERT? 'Cause if you want the ID from the second query then you should put it after the second query, not after the third. |
They're all inserts? There's no selects, updates, etc... Just inserts.
|
Actually, i just took a look at my query's and realised the problem is the first bit seen as php doesn't like giving line numbers of mysql errors. It's all fixed now, thanks for your help :D
|
Incidentally, you can often solve an odd problem like this by using straight SQL, e.g.
(using SQL to retrieve the ID value and store as a variable) Code:
SELECT @last_id:= LAST_INSERT_ID(); |
Problem is, by the time that's called another record might have alread been inserted causing you to get an unexpected output.
|
Isn't mysql_insert_id() a little dangerous if multiple people are using the system?
|
Not really, it gets the id of exactly the last query, if you run it straight after the query that is. If you select last_inserted_id then chances are it'd be dangerous.
|
Taken From: http://us3.php.net/mysql_insert_id
mysql_insert_id() converts the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT, the value returned by mysql_insert_id() will be incorrect. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. |
Quote:
Now, I need to update my scripts. :-) |
Repped and thanked :-) I must admit that I didn't even know that, and so it's a good piece of information to have!
|
Thanks!
Thanks guys. Glad to help out. I too have some "updating" to do.
Jon |
| All times are GMT. The time now is 05:17 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0