[英]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);
這是插入的代碼,如何獲取此行的ID? 這是一個自動增量。
從您的代碼中不清楚您正在使用哪個DB抽象庫(如果有的話)。它可能有自己的方法來獲取最后插入的id。
此外,mysql_insert_id()僅在您使用標准mysql庫時才有效。 例如,如果您使用mysqli,這可能會更好:
$last_id = $this->con->insert_id;
$id = mysql_insert_id();
你試過$id = mysql_insert_id($con);
或$id = $con->insert_id();
?
mysql_insert_id返回最后插入的記錄的id 更多信息
<?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());
?>
插入后只需調用mysql_insert_id()
。
你也可以
SELECT last_insert_id();
在一個單獨的查詢中,如果你正在做的任何DB庫沒有自己的方法(通常只是發出這個查詢)。 只要您使用相同的DB句柄,就可以保證獲得上次執行的插入操作的ID。
很簡單,通過id desc定期選擇訂單
這樣的事情
"SELECT * FROM tu_cla_facets ORDER BY id DESC LIMIT 1"
mysql_insert_id僅在您在腳本中插入時才有效
編輯:這將始終獲得最后插入的行,在某些罕見的情況下,但可能不必是您剛剛插入的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.