[英]How to create select option from database?
I'm working on a form that has 4 different select elements from 2 tables of a database. 我正在处理一个表单,该表单具有来自数据库2个表的4个不同的select元素。 I haven't done anything like this and I don't really know how to do it.
我还没有做过这样的事情,我也不知道该怎么做。
I have a table called "students" from I need "name" and "class" and a table called "books" from I need "writer" "title" ... all is one select element and all has more than 2 option values. 我有一个名为“ students”的表,我需要一个“名称”和“ class”,一个名为“ books”的表,我需要“作家”,“标题”……都是一个选择元素,并且都具有两个以上的选项值。
I've tried with only one sql query and one select but it shows only one option on the site, wether it has about 6 values in the database. 我只尝试了一个sql查询和一个select,但是它只显示站点上的一个选项,而且它在数据库中大约有6个值。
My code: 我的代码:
$sql = "SELECT class
FROM students";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
}
<select id="class" name="class">
<?php print $select_class; ?>
</select>
How would it be correct? 怎么会正确呢?
try this 尝试这个
$sql = "SELECT class FROM students";
$result = mysql_query($sql);
echo '<select id="class" name="class">';
while ($row = mysql_fetch_assoc($result)) {
echo "<option value={$row['class']}>{$row['class']}</option>";
}
echo '</select>';
Changing this: 改变这个:
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
to this: 对此:
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
might solve your problem. 可能会解决您的问题。
Right now you are constantly resetting the value of $select_class, instead of adding to it. 现在,您正在不断重置$ select_class的值,而不是添加到其中。 The .= assignment should help you get around this.
。=分配应该可以帮助您解决此问题。
As always, be sure to up-vote any StackOverflow answers you find useful. 与往常一样,请确保对您认为有用的所有StackOverflow答案进行投票。
You are overwriting $select_class
on each while()
loop. 您将在每个
while()
循环中覆盖$select_class
。 You need to concatenate $select_class
. 您需要连接
$select_class
。 Change to $select_class .=
更改为
$select_class .=
$select_class = "";
while ($row = mysql_fetch_assoc($result)) {
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
}
Try this 尝试这个
<?php
$dbhandle = mysql_connect($hostname, $username, $password) or die("can't connect");
$table = "students";
$sql = "SELECT * FROM students";
$result = mysql_query($sql, $dbhandle);
mysql_data_seek($result, 0);
?>
<form>
<select class="dropdown" name="dropdown">
<?php
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['class'] . '">' . $row['class'] . '</option>';
}
}
?>
</select>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.