我在这里使用数据库中的数据填充下拉列表中的代码。它工作正常,但我卡在获取用户的选定项目并将其放在变量中,有人可以帮助吗?这是代码:
<?php
// declare database connection variables.
$host = "localhost";
$username = "root";
$password = "";
$db_name = "sample";
$tbl_name = "tbl_company";
// connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT type FROM $tbl_name";
$result = mysql_query($sql) or die(mysql_error());
$dropdown = "<select name='items' class='select'>";
while ($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['type']}'>{$row['type']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
最佳答案
根据您的上述评论,您似乎做错了,将代码更改为:
<?php
// declare database connection variables.
$host = "localhost";
$username = "root";
$password = "";
$db_name = "sample";
$tbl_name = "tbl_company";
// connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT type FROM $tbl_name";
$result = mysql_query($sql) or die(mysql_error());
$dropdown = "<form action='' method='post'>"; //form tag added here,
//this is absolutely needed
$dropdown .= "<select name='items' class='select'>";
while ($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['type']}'>{$row['type']}</option>";
}
$dropdown .= "\r\n</select>";
$dropdown .= "<input type='submit' name='submit' value='Submit'>";
$dropdown .= "</form>"; //closing the form tag
echo $dropdown;
//checking if user has submitted the form
if(isset($_POST['submit']))
{
$var = $_POST['items'];
echo $var;
}
?>
编辑:
根据OP的以下评论:
$dropdown = "<form action='' method='post'>"; //form tag added here,
//this is absolutely needed
while ($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<input type='checkbox' name='items[]' value='{$row['type']}'>{$row['type']}";
}
$dropdown .= "<input type='submit' name='submit' value='Submit'>";
$dropdown .= "</form>"; //closing the form tag
echo $dropdown;
//checking if user has submitted the form
if(isset($_POST['submit']))
{
//$_POST['items'] is now a multi dimensional array
//because we named our checkboxes as items[]
//if you don't understand how, learn about input array
//it's a little long to be explained here
//therefore, you need the foreach statement to retrieve its values
foreach($_POST['items'] as $var){
echo $var; //prints all the checked values
}
}