[英]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.