Reputation: 1512
I have a simple question.
I'm putting info into a MySQL with PHP and I have an auto_increment field that I'm leaving alone.
How do I get the value of the auto_increment field in the row I just entered?
Upvotes: 0
Views: 599
Reputation: 3661
Here's three different approaches, from three commonly used libraries that can interface with MySQL (mysql, mysqli, pdo)
mysql_insert_id(...)
[procedural function]
mysqli::$insert_id
[OOP property]
PDO::lastInsertId(...)
[OOP method]
Upvotes: 1
Reputation: 32145
PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
Upvotes: 1
Reputation: 6992
SELECT MAX(that_field) AS last_auto_increment_value FROM that_table;
OR
SELECT auto_increment -1 AS last_auto_increment_value
FROM information_schema.tables
WHERE table_name='that_table'
AND table_schema = 'that_database';
OR
mysql_insert_id() //in PHP
Upvotes: 0
Reputation: 9299
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Upvotes: 1
Reputation: 5067
Here you go:
mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Upvotes: 1