如何使用HTML列表框和SQL代码显示表中的某些列?

问题描述 投票:-1回答:2

美好的一天,我有以下要求:一个有两列的表:国家和资本。该表包含来自世界各地的每个国家。有一个列表框,我可以在其中选择国家/地区,它将仅显示该国家/地区的资金。

我用HTML创建了一个列表框,让我选择一个国家:

< select> <br>
< option Country = "Brasil"> Brasil < /option> <br>
< option Country = "... "> .. < /option> <br>
< /select> </br>

如何使用该HTML列表框中的国家/地区显示资金?我想为每个资本创建一个选项,但是我需要超过120个if-cases。 (在SQL中)

html mysql sql
2个回答
0
投票

您可以生成选择表单:

<?php 
$req = $pdo->query('SELECT * FROM table');
$rep = $req->fetchAll(); ?>
<select>
foreach($rep as $row) { ?>
  <option value="<?= $row['country'] ?>"><?= $row['country'] ?></option>
<? } ?>
</select>
<?php foreach($rep as $row) { 
  <input style="display:none" id="<?= $row['country'] ?>" value="<?= $row['capital'] ?>" />
<?php } ?>

因此,您将拥有所有国家/地区的选择,以及每个Capital的输入,其国家/地区为ID,因此您可以使用javascript显示它:(jQuery示例)

<script>
$('select').change(function() {
  $('input:visible').toggle(); 
  $('input[id='+$(this).val()+']').toggle();
});
</script>

0
投票

您可以使用qazxsw poi中的以下代码从数据库中获取国家/地区及其首都

php

接下来,您将制作HTML //This is where you put the fetched data $entries = Array(); //Make new connection $connection = new mysqli("127.0.0.1", "username", "password", "databasename"); //Create prepared statement $statement = $connection->prepare("SELECT `country`, `capital` FROM `table`"); $statement->bind_result($country, $capital); //Put the fetched data in the result array while($statement->fetch()) { $entry = Array(); $entry['country'] = $country; $entry['capital'] = $capital; $entries[] = $entry; } //Close the statement and connection $statement->close(); $connection->close(); 对象。重要的是,国家的秩序与首都的顺序保持一致。

select

最后,向<!-- Country selection --> <select id="select-country"> <?php $i = 0; foreach ($entries as $c) { ?> <option data-country="<?php echo $i++; ?>"><?php echo $c['country'] ?></option> <?php } ?> </select> <!-- Capitals select --> <select id="select-capital"> <?php $i = 0; foreach ($entries as $c) { ?> <option data-capital="<?php echo $i++ ?>"><?php echo $c['capital'] ?></option> <?php } ?> </select> 添加一个事件监听器,其id为select,您可以在其中监听select-country事件。调用后,将第二个change的选定索引更改为第一个。这就是订单保持不变的重要原因。

select
© www.soinside.com 2019 - 2024. All rights reserved.