Reputation: 31
I am a bit stuck on how to use return last ID using PDO. All the tutorials/answers I have found are based on it not being in a class so struggling to find an answer.
The code I've got is below. It all works apart from returning the last id. When returned true it inserts in database and redirects to another page. Am I using return ID correctly? And if so, how do I echo the ID on the page that the user is redirected to?
EDIT: thanks for the answers - I have updated the code to replace 'true' with return last id part. However, I am still struggling to return the ID, have added the new code below. The database insertion is working correctly, I am just struggling to output what is returned.
Thanks,
The database query:
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();
}
How I am trying to echo out the ID:
$itinerary = new Itinerary;
$template->ID = $itinerary->insertNewCustomer();
echo $ID->lastID;
New code to try and echo out 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';}
Upvotes: 0
Views: 377
Reputation: 2197
<?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;
}
// Out of function scope $itinerary = new Itinerary;
$template->ID = $itinerary->insertNewCustomer(); // Call to function
if($template->ID!==false){echo "Customer ID". $template->ID;}
else{
echo "Customer insertion failed";
}
Upvotes: 0
Reputation: 1716
The issue is because you are returning before running db->lastInsertId();
Change this:
//Execute
if($this->db->execute()){
return true;
} else {
return false;
}
//Get ID of new customer
$lastID = $this->db->lastInsertId();
To:
//Execute
if($this->db->execute()){
return $this->db->lastInsertId();
} else {
return false;
}
$itinerary->insertNewCustomer();
will now return false on failed execute or the insert id.
Upvotes: 2