选择选项更改时,从数据库中显示选择选项

时间:2016-02-26 09:58:45

标签: php

<tr>
  <td><label class="label label-success">Building Name: </label></td>
  <td>
    <select class="form-control" name="building_name" required>
      <option value="">Select Building</option>
      <?php
      include '../Database/db.php';
      $res=mysql_query("SELECT * FROM building");
      while($row = mysql_fetch_array($res)){
      ?>
      <option value="<?php echo $row['building_name']; ?>"><?php echo $row['building_name']; ?></option>

      <?php } ?>
    </select>
  </td>
</tr>
<tr>
  <td><label class="label label-success">Floor: </label></td>
  <td>
    <select class="form-control" name="floor" required>
      <option value="">Select Floor</option>
      <option>></option>

    </select>
  </td>
</tr>

任何人都可以帮我,我想从数据库中显示所选建筑物的楼层。如果我选择建筑物,地板将显示在选择的楼层上。

2 个答案:

答案 0 :(得分:1)

在不知道您的数据库设置或结构的情况下,您将如何实现这一目标:

<?php require_once('../Database/db.php'); ?>
<tr>
  <td><label class="label label-success">Building Name: </label></td>
  <td>
    <select class="form-control" name="building_name" required">
      <option value="">Select Building</option>
      <?php
      $res=mysql_query("SELECT * FROM building");
      while($row = mysql_fetch_array($res)){
      ?>
      <option value="<?php echo $row['building_name']; ?>"><?php echo $row['building_name']; ?></option>
      <?php } ?>
    </select>
  </td>
</tr>
<tr>
  <td><label class="label label-success">Floor: </label></td>
  <td>
    <select class="form-control" name="floor" required>
      <option value="">Select Floor</option>
      <?php
      $building_name = mysql_real_escape_string($_POST['building_name']);
      $res2=mysql_query("SELECT * FROM floor WHERE building_id = '{$building_name}'");
      while($row = mysql_fetch_array($res2)){
      ?>
      <option value="<?php echo $row['floor_name']; ?>"><?php echo $row['floor_name']; ?></option>
      <?php } ?>
    </select>
  </td>
</tr>

您需要将已发布的参数传递给SQL中的WHERE子句。请注意,您应该从发布的参数中转发恶意代码。

我还假设您在form代码中包含此html代码以及提交按钮

答案 1 :(得分:0)

您应该使用AJAX来获取要在DROPDOWN中显示的数据库值

$('#building_name').change(function(){
var building_name=  $('#building_name').val();
$.ajax({
url: "index.php", //Change it yours
type: "post",
data: {building_name: building_name}, 
success: function(data) {
    if(data != "false")
{
    $('#Floor').html(data); 
}
else{
alert("No value");}
}
});
});

PHP功能应该是

  $building_name = mysql_real_escape_string($_POST['building_name']);
  $res2=mysql_query("SELECT * FROM building  WHERE building_name = '{$building_name}'");
  while($row = mysql_fetch_array($res2)){
  echo '<option value="'.$row['floor_name'].'">'.$row['floor_name'].'</option>';
  }