What are the best practices for handling forms with dynamic input fields in PHP to store data efficiently?

When handling forms with dynamic input fields in PHP, it is important to dynamically generate the form fields based on user input and efficiently store the data in a database. One way to achieve this is by using arrays in the form field names to group related data together. This allows for easy iteration through the data and insertion into the database.

// Example of handling a form with dynamic input fields in PHP

// Assuming the form has input fields with names like "field_name[]"
// This allows multiple values to be submitted as an array

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Connect to database
    $conn = new mysqli("localhost", "username", "password", "dbname");

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

    // Extract and store data from dynamic input fields
    foreach ($_POST["field_name"] as $value) {
        $sql = "INSERT INTO table_name (column_name) VALUES ('$value')";
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }

    // Close database connection
    $conn->close();
}