[英]php mysql drop down list
我有一个PHP表单,显示MySQL表中的数据。 每行显然有不同的数据,我想要做的是有一个下拉列表,显示与每行中的数据条目相关的数据。
例如,假设我有两张桌子。 Fruit and Fruit_Colors,如下:
因此,如果我的PHP表单显示如下,名为fruits的MySQL数据将显示Fruit列中的数据。 然后根据“Fruit”字段中的PHP表单输出值从Fruit_Colors表中获取颜色。 所以每行的下拉列表会有所不同。
我的PHP表格语法是:
<table id="hor-minimalist-a">
<tr>
<th>ID</th>
<th>Fruit</th>
<th>Color</th>
</tr>
<? while($row = $fruits->fetch(PDO::FETCH_ASSOC)) { ?>
<tr>
<td><? echo $row['id']; ?></td>
<td><? echo $row['fruit']; ?></td>
<td><SELECT NAME="fruitcolor" id="fruitcolor">
<OPTION VALUE=0 >
*// what goes here???*
</option>
</SELECT>
</td>
</tr>
<? } ?>
</table>
任何建议如何完成这一点将不胜感激。 记住这个表最多可以有50行,因此需要一种动态的方法将'fruit'值传递给下拉列表。
我知道下拉列表的语法是:
function fruitcolor_dropdown($db)
{
$result = $db->query("select color from Fruit_Color where Fruit=*'outputted value'*");
return $result;
}
$colors= fruitcolor_dropdown($db);
while($row = $colors->fetch(PDO::FETCH_ASSOC)) {
$color=$row["color"];
$optionsfruitcolors.="<OPTION VALUE=\"$color\">".$color;
}
建议一如既往地受到赞赏。 谢谢并恭祝安康。
看一下这个。 我们创建一个函数来生成下拉选项。 它接受DB和fruit作为参数 - >循环并使DOM - >将它输出到浏览器。
PHP函数
function getColors($db, $fruit)
{
$result = $db->query(
sprintf("select color from Fruit_Color where Fruit = '%s'",
$fruit
)
);
$output = '';
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$output .= sprintf(
'<option value="%s">%s</option>',
$row['color'],
$row['color']
);
}
return $output;
}
模板
<? while($row = $fruits->fetch(PDO::FETCH_ASSOC)) { ?>
<tr>
<td><? echo $row['id']; ?></td>
<td><? echo $row['fruit']; ?></td>
<td><SELECT NAME="fruitcolor" id="fruitcolor">
<?php echo getColors($db, $row['fruit']); ?>
</SELECT>
</td>
</tr>
<? } ?>
当您可以在单个查询中进行连接和触发查询两次时,这是个坏主意 - 您可以看到演示
$query = "select f.*,group_concat(color SEPARATOR '|') as fcolor from fruit F Left join fruit_color fc using (fruit) group by fc.fruit";
以上将是您的查询,您将循环它如下所示:
<? while($row = $fruits->fetch(PDO::FETCH_ASSOC)) { ?>
<tr>
<td><? echo $row['id']; ?></td>
<td><? echo $row['fruit']; ?></td>
<td><SELECT NAME="fruitcolor" id="fruitcolor">
<OPTION VALUE=0 >
<?php
$array = explode("|", $fcolor);
$count = count($array);
for($loop=0;$loop<$count;$loop) {
echo "<option>".$array[$loop]."</option>";
}
?>
</option>
</SELECT>
</td>
</tr>
<? } ?>
在selectbox中使用它
function fruitcolor_dropdown($db)
{
$result = $db->query("select color from Fruit_Color where Fruit=*'outputted value'*");
return $result;
while($row = $colors->fetch(PDO::FETCH_ASSOC)) {
$color=$row["color"];
$optionsfruitcolors.="<OPTION VALUE=\"$color\">".$color;
}
}
<select name="fruitcolor" id="fruitcolor">
<?php $colors= fruitcolor_dropdown($db); ?>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.