[英]PDO return last ID in a class
我對如何使用PDO使用返回最后一個ID有點困惑。 我發現的所有教程/答案都基於它不在課堂上,因此很難找到答案。
我的代碼如下。 除了返回最后一個ID之外,這一切都起作用。 返回true時,它將插入數據庫中並重定向到另一個頁面。 我是否正確使用退貨ID? 如果是這樣,我如何在用戶重定向到的頁面上回顯ID?
編輯:謝謝你的答案-我已經更新了代碼,以用返回的最后一個id部分替換“ true”。 但是,我仍在努力返回ID,在下面添加了新代碼。 數據庫插入工作正常,我只是在努力輸出返回的內容。
謝謝,
數據庫查詢:
public function insertNewCustomer($data){
$this->db->query("INSERT INTO Customers (First_Name, Surname, Email) VALUES (:firstname, :surname, :email)");
//Bind Data
$this->db->bind(':firstname', $data['firstname']);
$this->db->bind(':surname', $data['surname']);
$this->db->bind(':email', $data['email']);
//Execute
if($this->db->execute()){
return true;
} else {
return false;
}
//Get ID of new customer
$lastID = $this->db->lastInsertId();
}
我如何嘗試回顯ID:
$itinerary = new Itinerary;
$template->ID = $itinerary->insertNewCustomer();
echo $ID->lastID;
嘗試回顯ID的新代碼:
if(isset($_GET['firstname'])){
$data = array();
$data['firstname'] = $_GET['firstname'];
$data['surname'] = $_GET['surname'];
$data['email'] = $_GET['email'];
if($itinerary->insertNewCustomer($data)){
echo $itinerary->insertNewCustomer();
} else { echo 'did not work';}
問題是因為您要在運行db->lastInsertId();
之前返回db->lastInsertId();
更改此:
//Execute
if($this->db->execute()){
return true;
} else {
return false;
}
//Get ID of new customer
$lastID = $this->db->lastInsertId();
至:
//Execute
if($this->db->execute()){
return $this->db->lastInsertId();
} else {
return false;
}
$itinerary->insertNewCustomer();
現在將在執行失敗或插入ID時返回false。
<?php
// Use this function
public function insertNewCustomer($data){
$this->db->query("INSERT INTO Customers (First_Name, Surname, Email) VALUES (:firstname, :surname, :email)");
//Bind Data
$this->db->bind(':firstname', $data['firstname']);
$this->db->bind(':surname', $data['surname']);
$this->db->bind(':email', $data['email']);
//Execute
if($this->db->execute()){
//Get ID of new customer
return $this->db->lastInsertId();
}
return false;
}
//超出函數范圍$ itinerary = new Itinerary;
$template->ID = $itinerary->insertNewCustomer(); // Call to function
if($template->ID!==false){echo "Customer ID". $template->ID;}
else{
echo "Customer insertion failed";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.