How can PHP arrays and foreach loops be utilized to streamline the process of updating database fields from HTML form inputs?

When updating database fields from HTML form inputs, PHP arrays and foreach loops can be utilized to streamline the process by dynamically handling multiple form inputs. By using arrays to store form input values and iterating over them with a foreach loop, you can easily update corresponding database fields without writing repetitive code for each input field.

// Assuming form inputs are submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Connect to database
    $conn = new mysqli($servername, $username, $password, $dbname);

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

    // Define an array of database fields to be updated
    $fieldsToUpdate = ["field1", "field2", "field3"];

    // Loop through the array and update each field with corresponding form input value
    foreach ($fieldsToUpdate as $field) {
        if (isset($_POST[$field])) {
            $value = $_POST[$field];
            $sql = "UPDATE table_name SET $field = '$value' WHERE condition";
            $conn->query($sql);
        }
    }

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