What are some best practices for handling multiple insert queries in PHP that require the ID from a previous insert?

When handling multiple insert queries in PHP that require the ID from a previous insert, it is best to use transactions to ensure data integrity. By using transactions, you can execute multiple queries as a single unit of work, allowing you to roll back all changes if an error occurs. Additionally, you can use the `lastInsertId()` method provided by PDO to retrieve the ID of the last inserted row.

<?php

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Begin a transaction
$pdo->beginTransaction();

try {
    // Insert the first record
    $stmt = $pdo->prepare("INSERT INTO table1 (column1) VALUES (:value1)");
    $stmt->execute(['value1' => 'data1']);
    
    // Get the ID of the first insert
    $firstId = $pdo->lastInsertId();
    
    // Insert the second record using the ID from the first insert
    $stmt = $pdo->prepare("INSERT INTO table2 (column1, column2) VALUES (:value1, :value2)");
    $stmt->execute(['value1' => 'data2', 'value2' => $firstId]);
    
    // Commit the transaction
    $pdo->commit();
    
    echo "Records inserted successfully!";
} catch (Exception $e) {
    // Roll back the transaction if an error occurs
    $pdo->rollBack();
    
    echo "Error: " . $e->getMessage();
}