Insert data into multiple tables using one form
To insert data into multiple tables using one form in PHP, you can use a single SQL statement with multiple INSERT INTO clauses, or you can use multiple individual SQL statements, one for each table.
Here is an example of using a single SQL statement with multiple INSERT INTO clauses:
<?php
$sql = "INSERT INTO table1 (column1, column2) VALUES ('$value1', '$value2');
INSERT INTO table2 (column1, column2) VALUES ('$value3', '$value4');
INSERT INTO table3 (column1, column2) VALUES ('$value5', '$value6')";
if ($conn->multi_query($sql) === true) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Watch a video course
Learn object oriented PHP
Here is an example of using multiple individual SQL statements:
<?php
$sql1 = "INSERT INTO table1 (column1, column2) VALUES ('$value1', '$value2')";
$sql2 = "INSERT INTO table2 (column1, column2) VALUES ('$value3', '$value4')";
$sql3 = "INSERT INTO table3 (column1, column2) VALUES ('$value5', '$value6')";
if ($conn->query($sql1) === true && $conn->query($sql2) === true && $conn->query($sql3) === true) {
echo "New records created successfully";
} else {
echo "Error: " . $sql1 . "<br>" . $conn->error;
echo "Error: " . $sql2 . "<br>" . $conn->error;
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
You should be careful with SQL injection when using these type of statements, you should use prepared statements to avoid it.