What are the best practices for handling foreign keys and inserts in PHP when dealing with intermediate tables?

When dealing with intermediate tables in a database schema, it's important to properly handle foreign keys and inserts to ensure data integrity. One best practice is to use transactions to group related SQL queries together and ensure that either all of them succeed or none of them do. This helps prevent inconsistencies in the database. Additionally, make sure to properly set up foreign key constraints in the database schema to enforce referential integrity.

// Example of handling foreign keys and inserts in PHP using transactions

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->beginTransaction();

    // Insert into main table
    $mainTableQuery = $pdo->prepare("INSERT INTO main_table (column1, column2) VALUES (:value1, :value2)");
    $mainTableQuery->execute(array(':value1' => 'data1', ':value2' => 'data2'));
    $mainTableId = $pdo->lastInsertId();

    // Insert into intermediate table
    $intermediateTableQuery = $pdo->prepare("INSERT INTO intermediate_table (main_table_id, other_column) VALUES (:mainTableId, :otherValue)");
    $intermediateTableQuery->execute(array(':mainTableId' => $mainTableId, ':otherValue' => 'otherData'));

    $pdo->commit();

} catch (PDOException $e) {
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}