0

I have problem with LAST_INSERT_ID.

CREATE TABLE for_test(
id_test INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_name VARCHAR(30)
);

INSERT INTO for_test (test_name) VALUES ('test1');
INSERT INTO for_test (test_name) VALUES ('test2');

I added successfully two records - yet SELECT LAST_INSERT_ID() still returns 0. (I use InnoDB if that even matters)

Could anyone tell me what I'm doing wrong?

NSNoob
  • 5,320
  • 5
  • 35
  • 51
Petrus
  • 201
  • 1
  • 3
  • 14
  • have you tried using `mysql_insert_id()` – atoms Oct 07 '16 at 11:07
  • 1
    @atoms: mysql_insert_id is PHP function. on phpmyadmin it will return 0 always. Use it on procedure/function and you will get the result. – Riad Oct 07 '16 at 11:10
  • just a side note: the last_insert_id could also be the last inserted id from someone else from some other table. **unless* you use transactions!! – Krish Oct 07 '16 at 12:42

3 Answers3

2

No other query after insert and they both should execute together. Be careful that. Also if you can not handle it you can use

SELECT id FROM for_test ORDER BY id DESC LIMIT 1;

and you can read this manual

How to use LAST_INSERT_ID()

Onur Cete
  • 253
  • 1
  • 2
  • 9
0

you should try mysqli example

$sql = "INSERT INTO user (firstname, lastname, email)
VALUES ('test', 'test', 'test@example.com')";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
pawan sen
  • 708
  • 5
  • 14
0
CREATE TABLE for_test(
id_test INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_name VARCHAR(30)
);

INSERT INTO for_test (test_name) VALUES ('test1');
INSERT INTO for_test (test_name) VALUES ('test2');
SELECT LAST_INSERT_ID();

Note: it's working with Engine - InnoDB in phpMyAdmin. if you still have same problem, will you please send error snapshot, so that we can track exact issue.

Hope this will help you!!

Test1
  • 11
  • 4