How can PHP be used to dynamically select the correct table for storing form data based on user input?

When storing form data in a database, we may need to dynamically select the correct table based on user input. One way to achieve this is by using conditional statements in PHP to determine which table to insert the data into. By capturing the user input and checking it against predefined conditions, we can ensure that the data is stored in the appropriate table.

<?php
// Assuming $userInput contains the user input determining the table
$tableName = '';

if ($userInput === 'option1') {
    $tableName = 'table1';
} elseif ($userInput === 'option2') {
    $tableName = 'table2';
} else {
    $tableName = 'defaultTable';
}

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Insert data into the dynamically selected table
$sql = "INSERT INTO " . $tableName . " (column1, column2) VALUES ('value1', 'value2')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>