mn6vdv23g
mn6vdv23g

Reputation: 734

Get the AUTO_INCREMENT value after inserting a new row

How can I get the id that was just inserted for the current user if it is controlled by AUTO_INCREMENT?

(I need the Id for another use)

Note: some row can be deleted so MAX(id) is not an option.

Ex:

inserted row 2

inserted row 3

deleted row 3

inserted row 4 but MAX(id) returns 3..

Thank you very much!

Upvotes: 0

Views: 153

Answers (5)

Adarsh Nahar
Adarsh Nahar

Reputation: 319

Use mysql_insert_id() or mysqli_insert_id()

Upvotes: 0

Zerocool
Zerocool

Reputation: 1

you can use mysql_insert_id

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

EDIT:

mysql_insert_id is deprecated. now its mysqli_insert_id

Upvotes: -1

BlackBulletIV
BlackBulletIV

Reputation: 135

Since your answer is tagged with PHP, I'll answer in that context. If you're using the PDO API, you can use PDO::lastInsertId. If you're using the mysql function API, the equivalent would be mysqli_insert_id or mysql_insert_id.

Edit: Ninja'd :P

Upvotes: 0

Mark
Mark

Reputation: 1386

With PDO:

$db->lastInsertId(); // $db is the PDO object

With MySQLi OOP:

$db->insert_id; // $db is the MySQLi object

With MySQLi procedural:

mysqli_insert_id($db); // $db is the connection variable

If you're using the old MySQL API, switch.

Upvotes: 2

Shazoo
Shazoo

Reputation: 775

try

select @@identity

This should return the last value in the identity column

Upvotes: 0

Related Questions