mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$db->begin_transaction();
//first query
$sql = "INSERT INTO mytablename (colname1, colname2) VALUES (?, ?)";
$stmt = $db->prepare($sql);
$params = [$var1, $var2];
$stmt->execute($params);
if (empty($db->insert_id)) {
throw new Exception("Error1");
}
$last_id = $db->insert_id;
//second query
$sql = "INSERT INTO table2 (col1, col2, col3, col4) VALUES (?, ?, NOW(), ?)";
$stmt = $db->prepare($sql);
$params =[$one, $last_id,'some text'];
$stmt->execute($params);
if (empty($db->insert_id))
throw new Exception("Error2.");
}else{
$vv = $db->insert_id;
}
$db->commit();
} catch (mysqli_sql_exception $e) {
$db->rollback();
error_log("Error: (" . $e->getFile() . ":" . $e->getLine() . "): " . $e->getMessage());
echo "Error, try again";
}