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.
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;
Use the mysql_insert_id() function
$id = mysql_insert_id();
mysql_insert_id returns the id of the last inserted record more info here
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
<?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());
?>
Just call mysql_insert_id()
after insertion.
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.
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.
精彩评论