Is it possible to store data from a submitted form in two different SQL tables? If so, how can this be achieved in PHP?
Yes, it is possible to store data from a submitted form in two different SQL tables in PHP. This can be achieved by first inserting the data into one table and then using the inserted data to insert into the second table. This can be done by using PHP's MySQLi extension to establish a connection to the database, executing the insert query for the first table, retrieving the inserted data, and then executing another insert query for the second table.
<?php
// Establish connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Insert data into first table
$stmt = $mysqli->prepare("INSERT INTO table1 (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);
// Set values for the first table
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$stmt->execute();
// Retrieve the inserted data
$inserted_id = $mysqli->insert_id;
// Insert data into second table using the inserted data
$stmt2 = $mysqli->prepare("INSERT INTO table2 (column1, column2) VALUES (?, ?)");
$stmt2->bind_param("ss", $value3, $value4);
// Set values for the second table
$value3 = $inserted_id;
$value4 = $_POST['value3'];
$stmt2->execute();
// Close the statements and connection
$stmt->close();
$stmt2->close();
$mysqli->close();
?>
Keywords
Related Questions
- Are there any potential security risks associated with allowing a PHP website to display the currently playing music on a user's media player?
- What steps can be taken to ensure that MySQL queries in PHP return valid result resources to avoid errors during data retrieval?
- What are best practices for backing up PHP files and MySQL data before reinstalling XAMPP?