I tried the below code to get the last inserted id so as to insert it to another table but somehow using $this->$conn->lastInsertId()
doesn’t seem to work.
Anyone has any idea?
if (!( $stmt = $this->conn->prepare("INSERT INTO company(company_name,address_line1,address_line2,postal_code,country,contact_no,email,wifi_name,website_url,contact_person,parent_id,created_by,created_date,updated_date,deleted, wifi_name2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $this->conn->errno . ")" . $this->conn->error;
} else {
if (!$stmt->bind_param('ssssssssssiissis', $name, $address_line1, $address_line2, $postal_code, $country, $phone, $email, $wifi, $url, $contact, $p_id, $staff_id, $today, $updated, $deleted, $wifi2)) {
echo "Binding parameters failed: (" . $stmt->errno . ")" . $stmt->error;
} else {
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ")" . $stmt->error;
return FALSE;
} else {
echo $this->$conn->lastInsertId();
$stmt->close();
return TRUE;
}
}
}
2
Answers
For my case, which I believe I am not using the pdo accessing method, this works:
The code seems to be correct.
Maybe you don’t have the field
ID AUTOIMCREMENT PRIMARY
on that table.lastInsertId()
can return the new ID only if the field isAUTOIMCREMENT PRIMARY
.Try also do query this to see if you get the last inserted id:
If the aboves aren’t your case, you must analyze every single step to discover the issue:
id
field