Siddhant Rimal
Siddhant Rimal

Reputation: 978

Insert into two tables, one having foreign key of the other

I've looked at similar problems in SO and most of the solution were .NET centric and/or using stored procedures. So little help there. This is a snippet of the backend that I'm using to address an issue in my application.

$executestat=0;
//-------------------------
//PHASE-1
$sql = "INSERT INTO first_table (a_name,a_type,a_location) 
values('".$a_name."','".$a_type."','".$a_location."')";
if($result = $conn->query($sql)){
    $executestat=$executestat+1;
}
//-------------------------

//-------------------------
//PHASE-2
$sql = "SELECT f.a_id
from first_table as f
order by f.f_id desc limit 1";
if($result = $conn->query($sql)){
    $executestat=$executestat+1;
}
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $max_a_id = $row["a_id"];
    }
}else{$executestat=$executestat-1;}
//-------------------------

//-------------------------
//PHASE-3
$sql = "INSERT INTO second_table (a_id,b_title,b_location) 
values('".$max_a_id."','".$b_title."','".$b_location."')";
if($result = $conn->query($sql)){
    $executestat=$executestat+1;
}
//-------------------------

Problem Description:

How I'm handling it right now:

I have been told that this type of problem is handled, generally, by querying the first_table, in the second query, to get the most recent id and then using it, while inserting data in the third query, to insert into the second_table.

Whats going wrong

I took this advice from somebody who's been dealing with databases for a long time. I don't know if it's something I'm doing because, occasionally, only the first query runs (or so I think)*, failing the other queries completely.

tl;dr

Can someone point out what I'm doing wrong? A small snippet (modification of this; even better is complete revamp)

Upvotes: 2

Views: 766

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

After your insert, use $mysqli->insert_id; to get inserted value.

$sql = "INSERT INTO first_table (a_name,a_type,a_location) 
values('".$a_name."','".$a_type."','".$a_location."')";
if($result = $conn->query($sql)){
    $executestat=$executestat+1;
}
$max_a_id = $conn->insert_id;
//----

Upvotes: 1

Related Questions