0

Possible Duplicate:
PHP: how to get last inserted ID of a table?

I am having a problem with my MySQL insert. I have an Id column that is AUTO_INCREMENT and I run this code into that table:

mysql_query("INSERT INTO tickets (Submitted, UNIXtime, Subject, Text, User, Priority, Status, Service) VALUES ('$date', '$UNIXtime', '$subject', '$text', '$userss', '$priority', '$status', '$service')");

It then inserts an Id number in that row. How would I get that ID number so I can echo it out for example $id = (The ID number from that submit); echo $id;?

Thanks for the help. If you could, can you rewrite the code to make it work and post it so I know what to do?

Community
  • 1
  • 1
  • @AdrianCornish I just wanted someone to also help rewrite my code in context – William Burnside Nov 22 '11 at 02:05
  • @Darayus - fair enough - but maybe then you should have phrased your question "How do I rewrite my got to use last insert id*" I am learning stackoverflow is now just for answer a question but providing historical answers to the "same" question – Adrian Cornish Nov 22 '11 at 05:39
  • @AdrianCornish Did you read the last linke of my question? "If you could, can you rewrite the code"? – William Burnside Nov 22 '11 at 07:30

4 Answers4

4

You're looking for mysql_insert_id(). This function will return the ID of the last query.

You could call it after running your query:

mysql_query( $insert_query );
echo "Last ID is " . mysql_insert_id();
Sampson
  • 265,109
  • 74
  • 539
  • 565
2

You can use mysql_insert_id to get the last ID from the table. Note: You have to call mysql_insert_id right after the insert as it works only on the last executed query.

$id = mysql_insert_id();
halfdan
  • 33,545
  • 8
  • 78
  • 87
2

With mysql_insert_id();

http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

//Example
$id = mysql_insert_id(); 
echo $id;
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

mysql_insert_id()

Tim
  • 813
  • 5
  • 14
  • Wow.. this is why I never post answers on this site anymore. In the time it took me to type in my answer 2 other answers of the same thing had already been posted... – Tim Nov 22 '11 at 01:59
  • 4
    Tim, just take your time to answer questions. Even if someone posts before you it doesn't mean that the answer is better or even correct. – halfdan Nov 22 '11 at 02:00
  • try answering hard questions, no one will bother you there :) – Máthé Endre-Botond Nov 22 '11 at 02:02
  • @halfdan is absolutely correct. Write a great answer; you'll receive votes regardless of how quickly it was posted. – Sampson Nov 22 '11 at 02:02
  • Ah.. I knew I was having deja vu, I answered this question a couple of years ago too.. http://stackoverflow.com/questions/1358781/accessing-last-created-row-in-php-mysql/ :) And yeah, the "write good answers" thing is right. I hate feeling rushed here, not sure why I do.. heh. – Tim Nov 22 '11 at 04:26