如何从下拉列表中在 PHP/MySQL 中插入数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12276735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to insert a data in PHP/MySQL from a drop down?
提问by jericho morales
here is my form
这是我的表格
<select name="gender" id="gender">
<option>Select One</option>
<option>Male</option>
<option>Female</option>
</select>
i want to insert the data from the list, insert new data, and also when i edit the information
我想从列表中插入数据,插入新数据,以及当我编辑信息时
thanks in advance
提前致谢
回答by user1614526
first put this select inside html form give some action to form
首先把这个选择放在 html 表单中,给表单一些动作
<form action ="register.php" name="myform" method = "POST">
<select name="gender" id="gender">
<option value="">Select One</option>
<option value = "M">Male</option>
<option value = "F">Female</option>
</select>
</form>
on your register.php file use this to get the select value
在您的 register.php 文件中使用它来获取选择值
$gender = $_POST["gender"];// chose whetever your form method
$gender = $_POST["gender"];// 选择你的表单方法
establish the database connection please do refer some tutorials (if you don't know )
建立数据库连接请参考一些教程(如果你不知道)
write the mysql insert command like
编写mysql插入命令,如
$SQL = "INSERT INTO yourtable (gender) VALUES ('$gender')";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
now you can insert this value in your mysql or any database table
现在您可以将此值插入到您的 mysql 或任何数据库表中
this is not tested
这没有经过测试
回答by Pramod Kumar Sharma
Try this code
试试这个代码
<?php
mysql_select_db("my_db", $con);
$gender = $_POST["gender"];
mysql_query("INSERT INTO table_name(gender) VALUES ($gender)");
?>
回答by blasteralfred Ψ
Have a look at PHP MySQL: Creating Form Insert Dataand Processing form data with PHP. Useful for beginners.
看看PHP MySQL:使用 PHP 创建表单插入数据和处理表单数据。对初学者有用。
For your question you may either use $_POST["gender"]or $_GET["gender"]to grab dropdown data in your php file (to where the form targets or simply the php file inside your form action ="your_php_file.php") according to the methodof your form.
对于您的问题,您可以根据您的表单使用$_POST["gender"]或$_GET["gender"]抓取您的 php 文件中的下拉数据(表单目标位置或表单内的 php 文件action ="your_php_file.php")method。

