![](/img/trans.png)
[英]How to get the ID of the last inserted row in the table in MySql with PHP
[英]How to get last id inserted to mysql using OOP PHP?
我有以下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();
}
}
用於向數據庫添加內容的代碼:
$db = new db();
$success = $db->db_connection->query(
"INSERT INTO users(
name
)
VALUES(
'".$_POST["firstname"].'
)"
);
獲取插入元素的ID:
if($success){
$user_id = $db->db_connection->insert_id;
echo $user_id; // outputs 0
}
即使我在數據庫中有幾個條目,我得到的值為0,還有另外一種方法嗎? id也在表上有AUTO INCREMENT
注意:代碼是簡單的,而不是整個結構,但足以解釋真正的問題。
為什么要將INSERT與輪詢插入ID分開? 在這兩種情況下,失敗意味着您沒有添加行。 如果你在中間使用數據庫鏈接做任何其他事情,你將遇到可能正在發生的事情的復雜情況。
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.