Reputation: 978
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;
}
//-------------------------
a_id
which is the foreign-key from first_table. (a_id
is auto-increment primary-key on the first_table)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.
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.
if($executestat==3)
. So I know that the first-query runs(because the Db gets updated with the first_table insertion) but I'm not sure if the second query is running or not. However, I do know that atleast one but not all queries are running. Is there a way to echo errors into a file in PHP. That'd be great for thisa_id
of the other.a_id
in the second query, using $max_a_id
to insert into second_table in the third query.$max_a_id
a bad approach? Can anyone tell me a better way?Can someone point out what I'm doing wrong? A small snippet (modification of this; even better is complete revamp)
Upvotes: 2
Views: 766
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