[英]How to get last id inserted to mysql using OOP PHP?
I have the following PHP class, im using this to connect to db and make a new instance: 我有以下PHP类,我使用它来连接到db并创建一个新实例:
class db{
public $db_connection;
public function __construct(){
$this->db_connection = new mysqli("127.0.0.1","user","passwd","table");
$this->db_connection->set_charset("utf8");
if($this->db_connection->connect_errno) {
echo "Failed to connect to database: " . $db_connection->connect_error;
}
}
public function __destruct(){
return $this->db_connection->close();
}
}
The code im using to add stuff to the database: 用于向数据库添加内容的代码:
$db = new db();
$success = $db->db_connection->query(
"INSERT INTO users(
name
)
VALUES(
'".$_POST["firstname"].'
)"
);
Get the ID of the inserted element aboue: 获取插入元素的ID:
if($success){
$user_id = $db->db_connection->insert_id;
echo $user_id; // outputs 0
}
I am getting the value 0 even tho i have several entries in the database, is there another way around this? 即使我在数据库中有几个条目,我得到的值为0,还有另外一种方法吗? The id also have AUTO INCREMENT on the table id也在表上有AUTO INCREMENT
Note: Code is simplefied, and not the whole structure, but enough to explain the real issiue. 注意:代码是简单的,而不是整个结构,但足以解释真正的问题。
Why are you separating the INSERT from polling the insert id? 为什么要将INSERT与轮询插入ID分开? In both cases a failure means you haven't added a row. 在这两种情况下,失败意味着您没有添加行。 If you do anything else with the database link in between you'll run into complications which may be what is happening here. 如果你在中间使用数据库链接做任何其他事情,你将遇到可能正在发生的事情的复杂情况。
if ($db->db_connection->query($insert)) {
$user_id=$db->db_connection->insert_id;
} else {
// add some error handling/logging
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.