如何从html表单的下拉列表中获取所选选项的值到mysql数据库中?

时间:2014-12-03 02:04:19

标签: mysql database forms select html.dropdownlistfor

拥有一个带有下拉列表的表单,其中第一个选项由defualt选中。如何获取用户在我的数据库中选择的值?在此先感谢您的帮助?

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>

在PHP文件中

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

else {$extrafield5 = '';}

1 个答案:

答案 0 :(得分:1)

以下是具有类似要求的示例段(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>

根据游览要求进行适当的更改。 这里PHP代码写在同一个文件中(否则使用.php文件名指定表单操作)。