簡體   English   中英

PHP MYSQL動態選擇框

[英]PHP MYSQL dynamic select box

我正在嘗試創建一個搜索框,其中從“ 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]

提前致謝!

如上所述,首先使用php創建no1選擇菜單。 然后向其添加一個“更改” eventListener,如下所示:

$('#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菜單根據select 1 selected選項具有新選項。

和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/一個有效的示例

嘗試這個:

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.

謝謝!

也許您可以創建一個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>

謝謝

您應該嘗試一下;

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM