I have two tables: Incidents and Investigations
Incidents is my primary table and when I open a new case most of the information is inserted here. What I need is in the Investigations table to insert some of the information from the primary table. Both tables have id as they Primary Key and both ID's has auto increment. I am not much concerned about the ID in Investigations as this is not used much.
What I am trying to do is once the Incidents row is created it should take the id (Primary Key) and insert it automatically into Investigations table under column case_id and some of the other info I pass thru.
Will I be able to do this using PHP insert?
Current Code:
$sql = "INSERT INTO stinghs.incident SET
date = '".$date."',
time = '".$time."',
corrective = '".$corrective."',
status = 'Open'";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
$sql1 = "INSERT INTO stinghs.investigation SET
date = '".$date."',
time = '".$time."',
case_id = '".$case_id."',
status = 'Open'";
if ($conn->query($sql1) === TRUE) {
} else {
echo "Error: " . $sql1 . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
I am battling as this runs one after each other and there is no ID yet assigned or drawn as case_id?
UPDATE AND CORRECT CODE:
$sql = "INSERT INTO stinghs.incident SET
date = '".$date."',
time = '".$time."',
corrective = '".$corrective."',
status = 'Open'";
if ($conn->query($sql) === TRUE) {
$last_id = mysqli_insert_id($conn); //Retrieve the last ID of the record
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
$sql1 = "INSERT INTO stinghs.investigation SET
date = '".$date."',
time = '".$time."',
case_id = '".$last_id."',
status = 'Open'";
if ($conn->query($sql1) === TRUE) {
} else {
echo "Error: " . $sql1 . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
$case_id
would be the mysql last insert id on your connection object. https://www.php.net/manual/en/function.mysql-insert-id.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.