Ahmad Farid
Ahmad Farid

Reputation: 14774

How to get the ID of the last inserted row in the table in MySql with PHP

$sql="INSERT INTO tu_cla_facets VALUES(null,\"".addslashes($facet)."\",\"".addslashes($description)."\",\"".$parentId."\",\"\",\"".addslashes($leafFacet)."\",\"".addslashes($hidden)."\",\"\",'',NOW(),\"".$username."\",NOW(),\"".$username."\",\"\",\"\");";        
        $res=$this->con->query($sql);

This is the code of inserting, how to get the ID of this row? It's an auto-increment.

Upvotes: 2

Views: 6495

Answers (8)

Spudley
Spudley

Reputation: 168803

Have you tried $id = mysql_insert_id($con); or $id = $con->insert_id(); ?

http://www.php.net/manual/en/mysqli.insert-id.php

http://www.php.net/manual/en/function.mysql-insert-id.php

Upvotes: 2

Breezer
Breezer

Reputation: 10490

well simple make a regular select order by id desc

something like this

"SELECT * FROM tu_cla_facets ORDER BY id DESC LIMIT 1"

the mysql_insert_id will only work if you during the script made an insert

edit: this will always get the last inserted row which in some rare cases but possible doesn't has to be the very row you just insert.

Upvotes: -1

Marc B
Marc B

Reputation: 360832

You can also do

SELECT last_insert_id();

in a seperate query, if whatever DB library you're doing doesn't have its own method for this (which generally just issue this query anyways). As long as you're using the same DB handle, you're guaranteed to get the ID of the last insertion opereration performed.

Upvotes: 1

Svemir Brkic
Svemir Brkic

Reputation: 520

It is not clear from your code which DB abstraction library you are using (if any.) It may have its own method for obtaining last inserted id.

Also, mysql_insert_id() will work only if you use standard mysql library. If you use mysqli, for example, this may work better:

$last_id = $this->con->insert_id;

Upvotes: 3

user466764
user466764

Reputation: 1176

mysql_insert_id returns the id of the last inserted record more info here

Upvotes: 2

Andy
Andy

Reputation: 17791

Use the mysql_insert_id() function

$id = mysql_insert_id();

Upvotes: 2

Simon
Simon

Reputation: 4585

Just call mysql_insert_id() after insertion.

Upvotes: 1

gotnull
gotnull

Reputation: 27224

<?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());
?>

Upvotes: 1

Related Questions