PHP MYSQL 动态选择框

Posted

技术标签:

【中文标题】PHP MYSQL 动态选择框【英文标题】:PHP MYSQL dynamic select box 【发布时间】:2014-01-18 09:56:44 【问题描述】:

我正在尝试创建一个搜索框,其中从“box1”中选择的选项填充了“box2”可用的选项。这两个框的选项都来自我的 mysql 数据库。我的问题是我不知道如何在不刷新页面的情况下根据第一个查询执行查询,这将是乏味和烦人的。

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>

我认为查询会是这样的。 AJAX 可能是解决此问题的方法,但我不确定如何使用 AJAX 执行此查询而无需刷新。

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

提前致谢!

【问题讨论】:

查看 jQuery JSON。 【参考方案1】:

你应该试试这个;

search.php

<?php

// Check if the user wants the school or the school products (based on what the $.getJSON function sends us
if ( ! isset( $_GET['products'] ) && ! empty( $_GET['school'] ) ) 
    $sql_schools = mysqli_query( $con, "SELECT `name` FROM school" );
    $schools = '';
    while ( $school = mysqli_fetch_array( $sql_schools ) ) 
        $schools .= '<option value="' . $school['name'] . '">' . $school['name'] . '</option>';
    

// The user selected a school and now we will send back a JSON array with products, belonging to the specified school
else 
    $school = mysqli_real_escape_string( $_GET['school'] );
    $sql_products = mysqli_query( $con, "SELECT `product` FROM products WHERE school = '$school'" );
    $products = array();
    while ( $product = mysqli_fetch_array( $sql_products ) ) 
        // Note: If you use array_push() to add one element to the array it's better to use $array[] = 
        // because in that way there is no overhead of calling a function.
        // http://php.net/manual/en/function.array-push.php
        $products[] = $product['product'];
    

    header( "Content-Type: application/json" );
    echo json_encode( $products );
    die;


?>
<form role="form" action="search.php" method="GET">
      <div class="col-md-3">
          <select class="form-control" id="schools" name="school">
              <?= $schools; ?>
          </select>
      </div>
      <div class="col-md-3">
          <select class="form-control">
          </select>
      </div>
      <button type="submit" class="btn btn-info">Search</button>
</form>

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// When #schools gets changed to a new value, load the products belonging to that school
$('#schools').on('change', function() 
    $.getJSON('search.php?products&school=' + this.value, function(data) 
        var items = [];

        $.each(data, function(key, val) 
            items.push('<option value="' + val + '">' + val + '</option>');
        );

        $('#schools').empty().append(items);
    );
);
</script>

【讨论】:

这个解决方案看起来不错,但是当我将代码粘贴到其中时,只会给出一个没有表单的空白页面。你知道为什么会这样吗?【参考方案2】:

如上所述,首先使用 php 创建 no1 选择菜单。然后向它添加一个“更改”事件监听器,例如:

$('#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");
    

现在 no2 选择菜单根据 select 1 选择的选项有新的选项。

还有php文件:

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

当然,我使用了一些演示数据,但您可以进行一个 sql 查询,在那里填充 $data 数组并将它们作为带有正确标题的 json 发送。最后在第二个选择菜单中使用更多的 js:

$('#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");
    

在这里查看http://jsfiddle.net/g3Yqq/2/ 一个工作示例

【讨论】:

你能把我链接到 jsfiddle 请你只把我链接到网站的主页吗? 知道如何在 google chrome 扩展程序中进行这项工作吗?【参考方案3】:

也许您可以创建一个 javascript 二维数组,将关系学校保存到产品中。并且在选择学校名称时,可以通过学校名称作为数组中的键获取产品列表,并更新box2的选项列表。

也许你可以像这样回显一个 js 字符串:

<script language="javascript">
var array =  "school_name1" :  "product1", "poduct2" , "school_name2",  "product3", "product4"  ;
//you can get the product list by array['school_name1'], and you use js to update the product list
</script>

谢谢

【讨论】:

【参考方案4】:

试试这个:

You made one mistake here in select && option tag structure of HTML.
Just modify this and your code will work.

<select class="form-control" name="ddlist1">

&&

<?php
echo '<option value = "'.$row['name'].'">'.$row['name'].' School</option>';
?>

>> Add name property in select statement and value in place of name in option tag.

谢谢!

【讨论】:

以上是关于PHP MYSQL 动态选择框的主要内容,如果未能解决你的问题,请参考以下文章

如何在此代码中再添加一个动态链接选择框

动态依赖选择框(PHP+JQuery+AJAX)

通过 Ajax PHP 动态加载下拉选择

AJAX PHP+MySQL - 选择框

如何在 jsp 和 ajax 中为两个选择选项框动态地从 mysql 获取和填充值到 HTML 选择选项

使用 AJAX、PHP 和 MySQL 链式填充 HTML 选择框