Skip to content
PHP Logo

Are there any best practices or specific functions in PHP that can help streamline the process of inserting data into multiple tables?

When inserting data into multiple tables in PHP, one approach to streamline the process is to use transactions. By wrapping the insert statements in a transaction, you can ensure that either all inserts succeed or none do, maintaining data integrity. Additionally, using prepared statements can help prevent SQL injection attacks and improve performance.

php
<?php

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

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

try {
    // Insert data into table 1
    $stmt1 = $pdo->prepare("INSERT INTO table1 (column1, column2) VALUES (:value1, :value2)");
    $stmt1->execute(array(':value1' => 'data1', ':value2' => 'data2'));

    // Insert data into table 2
    $stmt2 = $pdo->prepare("INSERT INTO table2 (column1, column2) VALUES (:value1, :value2)");
    $stmt2->execute(array(':value1' => 'data3', ':value2' => 'data4'));

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