How can PHP developers ensure data integrity when handling multiple products in a shopping cart and inserting them into separate tables?

To ensure data integrity when handling multiple products in a shopping cart and inserting them into separate tables, PHP developers can use transactions. By wrapping the database operations in a transaction, all operations will either be completed successfully or rolled back if an error occurs, ensuring that the data remains consistent across tables.

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

try {
    // Insert product details into products table
    $stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (:name, :price)");
    $stmt->bindParam(':name', $productName);
    $stmt->bindParam(':price', $productPrice);
    $stmt->execute();

    // Get the last inserted product ID
    $productId = $pdo->lastInsertId();

    // Insert product ID and quantity into cart table
    $stmt = $pdo->prepare("INSERT INTO cart (product_id, quantity) VALUES (:product_id, :quantity)");
    $stmt->bindParam(':product_id', $productId);
    $stmt->bindParam(':quantity', $quantity);
    $stmt->execute();

    // Commit the transaction
    $pdo->commit();
} catch (Exception $e) {
    // Roll back the transaction if an error occurs
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}