douyue1998 2013-12-31 12:57
浏览 58
已采纳

PHP MYSQL动态选择框

I am trying to create a search box where the option selected from 'box1' populates the options available for 'box2'. The options for both boxes are given from my MYSQL database. My problem is that I do not know how to perform a query based on the first query without refreshing the page which would be tedious and annoying.

HTML / PHP

<form role="form" action="search.php" method="GET">
          <div class="col-md-3">
              <select class="form-control">
                  <?php
                  $result = mysqli_query($con,"SELECT `name` FROM school");
                  while($row = mysqli_fetch_array($result)) {
                    echo '<option name="'.$row['name'].'">'.$row['name'].' School</option>';
                  }

                  ?>
              </select>
          </div>
          <div class="col-md-3">
              <select class="form-control">
                  <?php
                  $result = mysqli_query($con,"SELECT * FROM products");
                  while($row = mysqli_fetch_array($result)) {
                    echo '<option name="'.$row['product'].'">'.$row['product'].'</option>';
                  }
                  mysqli_close($con);
                  ?>
              </select>
          </div>
          <button type="submit" class="btn btn-info">Search</button>
    </form>

I think that the query would go something like this. AJAX may be the solution to this problem but I am unsure how to use AJAX to perform this query without refreshing.

SELECT `product` FROM products WHERE `school` = [SCHOOL NAME FROM BOX 1]

Thanks in advance!

  • 写回答

4条回答 默认 最新

  • douyu7618 2013-12-31 13:22
    关注

    First create the no1 select menu with php as you mentioned above. Then add a 'change' eventListener to it like:

    $('#select1').change(createSelect2);
    
    function createSelect2(){
        var option = $(this).find(':selected').val(),
        dataString = "option="+option;
        if(option != '')
        {
            $.ajax({
                type     : 'GET',
                url      : 'http://www.mitilini-trans.gr/demo/test.php',
                data     : dataString,
                dataType : 'JSON',
                cache: false,
                success  : function(data) {            
                    var output = '<option value="">Select Sth</option>';
    
                    $.each(data.data, function(i,s){
                        var newOption = s;
    
                        output += '<option value="' + newOption + '">' + newOption + '</option>';
                    });
    
                    $('#select2').empty().append(output);
                },
                error: function(){
                    console.log("Ajax failed");
                }
            }); 
        }
        else
        {
            console.log("You have to select at least sth");
        }
    }
    

    Now the no2 select menu has new options according to the select 1 selected option.

    And the php file:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    
    if(isset($_GET['option']))
    {
        $option = $_GET['option'];
    
        if($option == 1)
        {
            $data = array('Arsenal', 'Chelsea', 'Liverpool');
        }
        if($option == 2)
        {
            $data = array('Bayern', 'Dortmund', 'Gladbach');
        }       
        if($option == 3)
        {
            $data = array('Aek', 'Panathinaikos', 'Olympiakos');
        }
    
        $reply = array('data' => $data, 'error' => false);
    }
    else
    {
        $reply = array('error' => true);
    }
    
    $json = json_encode($reply);    
    echo $json; 
    ?>
    

    Of course there i use some demo data but you can make an sql query populate the $data array there and send them as json with the right headers. Finally use some more js for the second select menu:

    $('#select2').change(selectSelect2);
    
    function selectSelect2(){
        var option = $(this).find(':selected').val();
        if(option != '')
        {
            alert("You selected: "+option);
        }
        else
        {
            alert("You have to select at least sth");
        }
    }
    

    Check here http://jsfiddle.net/g3Yqq/2/ a working example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100