How can PHP foreach() function be utilized to iterate through multiple form fields for SQL query construction?

When constructing an SQL query from multiple form fields, we can use the PHP foreach() function to iterate through the form field values and dynamically build the query. By looping through the form fields, we can extract the field names and values to construct the SQL query string.

// Assume $formData is an array containing form field names and values
$query = "INSERT INTO table_name (";
$values = "VALUES (";

foreach ($formData as $field => $value) {
    $query .= $field . ", ";
    $values .= "'" . $value . "', ";
}

$query = rtrim($query, ", ") . ") " . rtrim($values, ", ") . ")";
// Execute the SQL query using $query