I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?
Is it similar to SELECT MAX(id) FROM
It's sad not to see any answers with an example.
Using Mysqli::$insert_id:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$mysqli->query($sql);
$last_inserted_id=$mysqli->insert_id; // returns last ID
Using PDO::lastInsertId:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$database->query($sql);
$last_inserted_id=$database->lastInsertId(); // returns last ID
Try this should work fine:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "INSERT blah blah blah...";
$result = mysqli_query($link, $query);
echo mysqli_insert_id($link);
It's ok. Also you can use LAST_INSERT_ID()
What you wrote would get you the greatest id
assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.
PHP offers a specific function for that too called mysql_insert_id.
Use mysqli as mysql is depricating
<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* close connection */
$mysqli->close();
?>
there is a function to know what was the last id inserted in the current connection
mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();
plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.
That function is called mysql_insert_id