简体   繁体   English

动态填充两个 <select> SQL数据库列表

[英]Dynamically populating two <select> list from SQL database

I have a query about how to populate two separate lists from an SQL database, my database looks like this; 我有一个关于如何从SQL数据库填充两个单独列表的查询,我的数据库如下所示;

shoe_id      shoe_type       shoe_color
_________________________________________
001          Hi-Top          Blue
002          Loafer          Black
003          Brogue          Brown
004          Brogue          Black
005          Loafer          Brown
006          Loafer          Red
007          Hi-Top          Yellow

I'm wondering how to create a select list to display the shoe_type and the second one to dynamically change depending on the shoe_type, to show the shoe_color. 我想知道如何创建一个选择列表以显示shoe_type,并创建第二个列表以根据shoe_type动态变化以显示shoe_color。

For example, 'Brogue' is selected in the first select list and then both 'Brown' and 'Black' displayed in the second select list. 例如,在第一个选择列表中选择了“布朗”,然后在第二个选择列表中同时显示了“布朗”和“黑色”。

Thank you in advance. 先感谢您。

You can produce this structure based on your database if it is prefetched: 如果已预取,则可以根据数据库生成此结构:

shoes array(3) {
    ['Hi-Top'] => array(2) {
        [1] => 'Blue',
        [7] => 'Yellow'
    }
    ['Loafer'] => array(3) {
        [2] => 'Black',
        [5] => 'Brown',
        [6] => 'Red',
    }
    ['Brogue'] => array(2) {
        [3] => 'Brown',
        [4] => 'Black'
    }
}

and in HTML generator: 并在HTML生成器中:

<select name="type">
    <?php foreach($shoes as $shoeType => $shoeColors): ?>
        <option value="<?= $shoeType ?>" <?php if(isset($_POST['type']) && $_POST['type'] == $shoeType) echo 'selected="selected"'?>><?= $shoeType?></option>
    <?php endforeach; ?>
</select>
<select name="color">
    <?php if (isset($_POST['type']) foreach($shoes[$_POST['type']] as $k => $v): ?>
        <option value="<?= $k ?>" <?php if(isset($_POST['color']) && $_POST['color'] == $k) echo 'selected="selected"'?>><?= $v ?></option>
    <?php endforeach; ?>
</select>

Now if you could save $_POST['type'] and $_POST['color'] in the session to use later on, you'd never need JS at all and your code works even if JS is disabled on the browser. 现在,如果您可以在会话中保存$ _POST ['type']和$ _POST ['color']以便以后使用,则根本不需要JS,即使您的浏览器禁用了JS,代码也可以正常工作。

But if you like, you can use JS. 但是,如果您愿意,可以使用JS。 Json encode it and use it in your javascript. Json对其进行编码并在您的JavaScript中使用它。 Rather than that the only way is to use AJAX. 并非唯一的方法是使用AJAX。

var shoes = <?= json_encode($shoes) ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM