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
To get last inserted id in codeigniter
After executing insert query just use one function called insert_id()
on database, it will return last inserted id
Ex:
$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id
in one line
echo $this->db->insert('mytable',$data)->insert_id();
Using MySQLi
transaction I sometimes wasn't able to get mysqli::$insert_id
, because it returned 0. Especially if I was using stored procedures, that executing INSERT
s. So there is another way within transaction:
<?php
function getInsertId(mysqli &$instance, $enforceQuery = false){
if(!$enforceQuery)return $instance->insert_id;
$result = $instance->query('SELECT LAST_INSERT_ID();');
if($instance->errno)return false;
list($buffer) = $result->fetch_row();
$result->free();
unset($result);
return $buffer;
}
?>
It's ok to use mysql_insert_id()
,
but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session.
If you use it otherwise it wouldn't work correctly.
If you're using PDO, use PDO::lastInsertId.
If you're using Mysqli, use mysqli::$insert_id.
If you're still using Mysql:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
But if you have to, use mysql_insert_id.
You can get the latest inserted id by the in built php function mysql_insert_id();
$id = mysql_insert_id();
you an also get the latest id by
$id = last_insert_id();
NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.
The table:
create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));
Now if you do:
insert into xyz (name) values('one'),('two'),('three');
The mysqli::insert_id will be 1 not 3.
To get the correct value do:
mysqli::insert_id + mysqli::affected_rows) - 1
This has been document but it is a bit obscure.