Skip to content
PHP Logo

How can different values from select fields be inserted into a database using a submit button in PHP?

To insert different values from select fields into a database using a submit button in PHP, you need to retrieve the selected values from the select fields when the form is submitted and then insert these values into the database. This can be achieved by accessing the selected values using the $_POST superglobal array and then using SQL queries to insert the values into the database.

php
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve selected values from the select fields
    $value1 = $_POST['select_field1'];
    $value2 = $_POST['select_field2'];
    
    // Establish a connection to the database
    $conn = new mysqli("localhost", "username", "password", "database");
    
    // Check if the connection is successful
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // Insert the values into the database
    $sql = "INSERT INTO table_name (column1, column2) VALUES ('$value1', '$value2')";
    
    if ($conn->query($sql) === TRUE) {
        echo "Values inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    // Close the database connection
    $conn->close();
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <select name="select_field1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
    
    <select name="select_field2">
        <option value="value3">Value 3</option>
        <option value="value4">Value 4</option>
    </select>
    
    <input type="submit" value="Submit">
</form>