What are some best practices for handling form submissions with multiple input options, including the ability to add a new value if it is not already present in the database?

When handling form submissions with multiple input options, including the ability to add a new value if it is not already present in the database, it is important to validate the input data, check if the value already exists in the database, and insert a new value if necessary. One approach is to use a combination of dropdown menus for existing options and a text input field for new values.

<?php
// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selectedOption = $_POST["selectedOption"];
    $newOption = $_POST["newOption"];

    // Validate input data
    if (!empty($selectedOption)) {
        // Check if the selected option already exists in the database
        // If not, insert the new option into the database
        if (optionExists($selectedOption)) {
            // Handle existing option
        } else {
            insertOption($newOption);
            // Handle new option
        }
    } else {
        // Handle empty selection
    }
}

function optionExists($option) {
    // Check if the option exists in the database
    // Return true if exists, false otherwise
}

function insertOption($option) {
    // Insert the new option into the database
}
?>