0

I'm looking to be able to retrieve the last inserted id based on username. I know within PDO I am able to use to use lastInsertId() but from what I can tell that only gets the last one inserted with no other parameters. Is this possible in a short and simple?

The only way I thought I could do this was using something like

SELECT id FROM table_name WHERE username=:username ORDER BY enteredTimenDate ASC

Would this be the easiest way I could do this?

EDIT to address duplicate issue. The "Original" question this question is considered a duplicate of just asks how to retrieve the last inserted ID, my question was retrieving the last inserted ID based on another parameter.

John
  • 115
  • 10
  • `select max(id) `, presumably, with all the usual provisos for trying to implement your own id functions: racey, unreliable, almost always totally unecessary. – Marc B Jul 13 '15 at 17:26
  • So select max(id) from table_name where username:username should work? – John Jul 13 '15 at 17:33
  • Yes, you could use `SELECT MAX(id)` with the username as the filter. – Jay Blanchard Jul 13 '15 at 17:49
  • Brilliant, I will give this a go. If you would like to add it as an answer, I'll test it out and if it works as I need I'll accept it as the correct answer. – John Jul 13 '15 at 17:57

1 Answers1

0

Use following query to get the last inserted id:

SELECT id FROM table_name WHERE username=:username ORDER BY enteredTimenDate desc limit 1;

Data is sorted based on the enteredTimenDate in descending order and then picking up the first row by limiting the query result.

Abhishek Ginani
  • 4,511
  • 4
  • 23
  • 35