How to get value of selected option from a html form's dropdown list into mysql database?

倾然丶 夕夏残阳落幕 提交于 2019-12-12 02:06:50

问题


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).



来源:https://stackoverflow.com/questions/27262434/how-to-get-value-of-selected-option-from-a-html-forms-dropdown-list-into-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!