What role does SQL play in storing and retrieving data from a table filled by a PHP form?
SQL plays a crucial role in storing and retrieving data from a table filled by a PHP form. When a user submits a form, PHP processes the input data and then uses SQL queries to insert the data into a database table. To retrieve the data later, PHP again uses SQL queries to fetch the relevant information from the database table.
// Assuming the form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Establish a connection to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process form data
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
// Prepare SQL query to insert data into a table
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$data1', '$data2')";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the database connection
$conn->close();
}