Skip to content
PHP Logo

How can array data from a form submission be properly processed and inserted into multiple database tables in PHP?

When processing array data from a form submission in PHP, you can iterate through the array and insert the values into the respective tables in the database. You can use prepared statements to prevent SQL injection attacks and ensure data integrity. Make sure to establish a database connection before inserting the data.

php
// Assuming $formData is the array data from the form submission
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Insert data into the first table
$stmt = $pdo->prepare("INSERT INTO table1 (column1, column2) VALUES (?, ?)");
$stmt->execute([$formData['value1'], $formData['value2']]);

// Get the ID of the inserted row in table1
$table1Id = $pdo->lastInsertId();

// Insert data into the second table using the ID from table1
$stmt2 = $pdo->prepare("INSERT INTO table2 (column1, column2) VALUES (?, ?)");
$stmt2->execute([$table1Id, $formData['value3']]);