如何使用htmllistbox和sql代码显示表中的某些列?

du7egjpx  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(220)

你好,我有以下要求:一张有两列的表格:国家和首都。这个表格包含了世界上每个国家的每一个首都。有一个列表框,我可以选择国家,它将只显示该国的资本。
我用html创建了一个列表框,让我可以选择一个国家:

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

如何使用html列表框中的国家显示首都?我在考虑为每一笔资本创造一个选择,但如果是这样的话,我需要120多个(在sql中)

vjrehmav

vjrehmav1#

您可以生成选择窗体:

<?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 } ?>

因此,您将拥有selectwithallcountry,以及每个首都的一个输入,其国家作为id,这样您就可以用javascript显示它了:(jqueryexample)

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

avwztpqn2#

您可以使用中的以下代码从数据库中获取国家和其他国家的首都 php ```
//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();

接下来,创建html `select` 物体。重要的是国家的顺序和首都的顺序保持一致。

相关问题