获取从数据库中选择表单的选项


Get options for select in forms from database

我正在使用PHP编程服务器端,但被卡住了。

我想为表单创建一组使用选择标签的输入字段。选择的选项应该从我的数据库中获取,第一次输入中选择的选项将决定第二次输入中的选项。

例如,两个字段是country和state。首先,用户选择他们的国家名称,这将决定出现在状态输入字段中的州列表。当用户更改国家/地区时,我希望列表动态更改

您可以在PHP中每次提交一个select。

例如:

 <form action="selectState.php" method="post">
  <select name="country">
   <option value="countryName">countryName</option>
   ...
  </select>
 </form>

然后在selectState.php中获得$_POST['country']的值,并按您想要的方式打印选择:

 <form action="" method="post">
  <select name="state">
   <?php
     // select use $_POST['country'] to customize the select option's
   ?>
  </select>
 </form>

一个更用户友好的解决方案(不需要新页面或刷新)是使用AJAX

你可以用这种形式:

<form action="selectState.php" method="post">
  <select name="country" onchange="ajaxFunction(this.value)">
   <option value="countryName">countryName</option>
   ...
  </select>
  <select name="state" id="stateList">
   <!-- here we'll put the states we want -->
  </select>
 </form>

每次用户更改选择值时,ajaxFunction()被调用并传递给函数当前选择的值。

下面是ajaxFunction(注意:这个例子使用jQuery,但你可以在javascript中实现):

function ajaxFunction(val){
  $.ajax({
    type: 'post', // choose the method
    url: 'page.php', // choose the 'action' page
    data: {
      country:val // send the data
    },
    success: function (response) {
      // this tell the browser what to do with the response of 'page.php'
      // in this case we are telling to put everything we get to the HTML element with stateList id 
      document.getElementById("stateList").innerHTML=response;
    }
  });
}

你需要的最后一件事是'page.php',它只是查询数据库(注意:这是伪代码):

<?php
 // Query the DB for the states with country = $_POST['country']
 while(results){
  echo '<option value="results[$i]">results[$i]</option>';
 }
?>

您是否正在使用php框架,如Laravel(推荐)或Codeigniter(不确定是否仍在开发中)

如果是这样的话,你可以构建一个2d的php国家数组,每个国家都有一个国家的子数组。

可以直接放到呈现页面(视图)中。使用像

这样的东西
 var countries_list =<?php echo json_encode($countries_array); ?>;

将直接把它注入到一个javascript数组中,当国家选择发生变化时,你可以用它来填充状态选择。

或者使用ajax,但这会更慢,并且更多地访问服务器。
相关文章: