首页 > 解决方案 > 根据复选框填充下拉列表

问题描述

我有一个包含复选框和下拉列表的表单。我使用 PHP 从两个 MySQL 表中填充下拉列表。我使用哪个表取决于复选框是否被选中。但是,正如您从我的代码示例中看到的那样,我只能在提交表单后填充该下拉列表。我希望能够继续单击复选框并继续重新填充下拉列表,而无需提交表单。我还是新手,所以,请给我一个尽可能简单的解决方案。

PS。我的代码中有一个小错误,在我提交表单后不会选中/取消选中复选框。正在修复它。

谢谢


<?php
$Prc_Earn = 'Prc';
if (isset($_POST['submitBtn']))
  {
    if (isset($_POST['chkbox']))
      {
        $sql = 'select distinct Symbol from price_history.quarterly_earnings_history';
        $Prc_Earn = 'Earn';
      }
    else
      {
        $sql = 'select distinct Symbol from price_history.stock_symbol_list';
        $Prc_Earn = 'Prc';
      }
    }
// Connect to the database
include ('../Connections/mysql_connect.php');
if ($dbcon)
  {
?>
    <form method='post'>
        <label for=''>Earnings / Prices</label>
        <input type='checkbox' name='chkbox' id='chkbox' <?php if ($Prc_Earn == 'Prc') { echo "checked"; };?>><br><br>

        <label for='symbol'>Stock Symbol:</label>
        <select name = 'symbol' id='symbol'>
<?php
        $result = mysqli_query($dbcon, $sql);
        if (mysqli_num_rows($result) > 0)
          {
            while($row = mysqli_fetch_array($result))
              { echo '<option value="' . $row['Symbol'] . '">' . $row['Symbol'] . '</option>'; }
          }
?>
        </select><br><br>
        <button class='button' type='submit' name='submitBtn' id='submitBtn'>View Data</button><br><br>
    </form>
<?php
  }
?>

标签: phpforms

解决方案


推荐阅读