How to work with select tag in HTML and PHP

Viewed 39

I made a "productType" select tag. I added in phpmyadmin but when I click the submit button it gives me an error message

productType is undefined

and if add ?? null I'm bypassing the error but the selected value is null in phpmyadmin. Here's my html:

<form action="connect.php" method="post">
    <select id="productType" name="productType">
        <option value="">Select Type</option>
        <option value="d">DVD</option>
        <option value="b">Book</option>
        <option value="f">Furniture</option>
    </select>
</form>

And this is my PHP code:

<?php 
    $productType = $_POST["productType"];

    $conn = new mysqli('localhost', 'root', '', 'test');
    if($conn->connect_error){
        die("Connection Failed: " .$conn->connetion_error);
    }else{
        $stmt = $conn->prepare("Insert into ScandiwebTest(productType) values(?)");
        $stmt->bind_param("s", $productType);
        $stmt->execute();
        echo "Creation was successful!!";
        $stmt->close();
        $conn->close();
    }
?>
1 Answers

How to do you submit your form ? in your snippet there is no submit button to php. The first option should be

    <option selected disabled>Select Type</option>

and add a submit button to submit the form

    <form action="connect.php" method="post" >
        <select id="productType" name="productType">
            <option selected disabled>Select Type</option>
            <option value="d">DVD</option>
            <option value="b">Book</option>
            <option value="f">Furniture</option>
        </select>
        <button type="submit">
            submit
        </button>
    </form>

and result is

array(1) { ["productType"]=> string(1) "b" }
Related