I have two table, in table 1, there is an auto increment ID, I wanted to INSERT that last ID into table 2 right after the record was saved into table 1. Is it possible to do that. I have a form that the user fill up, the data collected was then submitted to two different table upon submission. This is my code for INSERTing the data
class.php
public function insertID(){
$query = "INSERT INTO table_1 SET book_name=:book_name; INSERT INTO table_2 SET
book_type=:book_type, book_type_id=:book_type_id";
$stmt = $this->conn->prepare($query);
$this->book_name=$this->name; //this data came from a form
$this->book_type=$this->book_type; //same as this one
$this->book_type_id=(Im not sure what to put here)(I tried LAST_INSERT_ID and
mysqli_insert_id)
//data the will go here should come from the last inserted ID so I connect table 1 and
table 2 using this ID
$stmt->bindParam(':book_name', $this->book_name);
$stmt->bindParam(':book_type', $this->book_type);
$stmt->bindParam(':book_type_id', $this->book_type_id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
here is my form
include_once 'class.php';
$class = new Class($db);
if($_POST){
$class->book_name=$_POST['book_name'];
$class->book_type=$_POST['book_type'];
if($class->insertId()){
echo "saved";
}else {
not saved
}
}
any suggestion would be greatly appreciated thank you.
Here is my solution with the help from @GMB
class.php
public function insertID(){
$query_1 = "INSERT INTO table_1
SET book_name=:book_name";
$stmt_1 = $this->conn->prepare($query_1);
$this->book_name=$this->book_name;
$stmt_1->bindParam(':book_name', $this->book_name);
if($stmt_1->execute()){
$query_2 = "INSERT INTO table_2
SET book_type=:book_type, book_type_id=:book_type_id";
$stmt_2 = $this->conn->prepare($query_2);
$this->book_type=$this->book_type;
$this->book_type_id=$this->conn->lastInsertId();
$stmt_2->bindParam(':book_type', $this->book_type);
$stmt_2->bindParam(':book_type_id', $this->book_type_id);
if($stmt_2->execute()){
return true;
}else{
return false;
}
}else{
return false;
}
}