php mysqli insert_id()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5844151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysqli insert_id()
提问by tonoslfx
I don't know, what's wrong in my code. I try to get the latest insert id, it's echoing 0. Any idea?
我不知道,我的代码有什么问题。我尝试获取最新的插入 ID,它是 0。知道吗?
public function __construct() {
$this->mysqli = new mysqli(MYSQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME) or die ('Error with connecting to the database!');;
}
public function insert_id(){
return $this->mysqli->insert_id;
}
$db->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name')");
var_dump($db->insert_id()); // return 0?
回答by Adnan
You should use it as follow:
您应该按如下方式使用它:
<?php
$mysqli = new mysqli(SQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME);
if ($result = $mysqli->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name');")) {
echo 'The ID is: '.$mysqli->insert_id;
}
?>
回答by user732694
The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
mysqli_insert_id() 函数返回对具有 AUTO_INCREMENT 属性的列的表的查询生成的 ID。如果最后一个查询不是 INSERT 或 UPDATE 语句,或者如果修改后的表没有具有 AUTO_INCREMENT 属性的列,则此函数将返回零。
Looks like you don't have a field with AUTO_INCREMENT attribute or if you have one you are not using it in the query.
看起来您没有具有 AUTO_INCREMENT 属性的字段,或者如果您有一个字段,则您没有在查询中使用它。