What are some considerations when updating database records based on dynamically generated form field values in PHP?

When updating database records based on dynamically generated form field values in PHP, it is important to properly sanitize and validate the input data to prevent SQL injection attacks. Additionally, you should dynamically construct the SQL query based on the form field values to ensure that only the necessary fields are updated.

// Sanitize and validate form field values
$field1 = filter_var($_POST['field1'], FILTER_SANITIZE_STRING);
$field2 = filter_var($_POST['field2'], FILTER_SANITIZE_STRING);

// Dynamically construct the SQL query
$query = "UPDATE table SET";
if(!empty($field1)) {
    $query .= " field1 = '$field1',";
}
if(!empty($field2)) {
    $query .= " field2 = '$field2',";
}
// Remove trailing comma
$query = rtrim($query, ',');
$query .= " WHERE id = $id";

// Execute the query
$result = mysqli_query($conn, $query);

if($result) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($conn);
}