-->

How to get value of selected option from a html fo

2019-09-07 05:46发布

问题:

Have a form with a dropdown list with the first option selected by defualt. How can I get the value the user selects into my data base? Thanks in advance for your help?

HTML FORMS DROP DOWN LIST:

<select name="extrafield5">
 <option value="NOW" selected="selected">Submit order now</option>
 <option value="REVIEW">Submit my order for review</option>

</select>

IN PHP FILE

if (isset($_POST['extrafield5'])){
    $extrafield5 = $_POST['extrafield5'];
}

else {$extrafield5 = '';}

回答1:

Here is a sample segment with a similar requirement(PHP-MySQL):

filename.php

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $tablename = "name_of_table";
    $db_name = "db_name";

    // Create connection
    $conn = new mysqli($servername, $username, $password);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
   }

    if (isset($_POST['extrafield5'])){
        $extrafield5 = $_POST['extrafield5'];
    }
    else {$extrafield5 = '';}
    $sql = "INSERT INTO $tablename (fieldname) VALUES('$extrafield5');";
    mysql_select_db($db_name);
    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
      die('Could not enter data: ' . mysql_error());
    }
    echo "Entered data successfully\n";
    mysql_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<title>PhpFiddle Initial Code</title>

<script type="text/javascript">
    /* Your scrips here */
</script>

<style type="text/css">
    /* Your css here */
</style>

</head>

<body>

<div style="margin: 30px 10%;">
    <h3>My form</h3>
    <form action="" method="post" id="myform" name="myform">
        <select name="extrafield5">
         <option value="NOW" selected="selected">Submit order now</option>
         <option value="REVIEW">Submit my order for review</option>
        </select>
        <input type="submit">
    </form>
</div>

</body>
</html>

Make appropriate changes according yo tour requirement. Here the PHP code is written in the same file(Otherwise specify the form action with the .php file name).