我有一个从数据库填充的选择元素,当我选择一个元素时,我想向我展示来自与该行相关的另一列的其他数据。

例如:
在下拉菜单中,我有:
苹果,
香蕉,


当我选择苹果时,我想从数据库中选择“总计”列,该列显示了我还剩下多少个苹果。

我认为,我应该使用Javascript-Ajax吗?还是用php做到这一点的另一种方法。

提前致谢!

<?php include("db.php"); ?>
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
    $(document).ready(function() {
        $('select').material_select();
    });

    function myFunction() {
        if (document.getElementById('selectid').value == "other") {
            var x = document.createElement("INPUT");
            x.setAttribute("type", "text");
            x.setAttribute("value", "");
            x.setAttribute("placeholder", "Write another");
            x.setAttribute("class", "input-field col s12");
            document.getElementById("myDIV").appendChild(x);
        }
    }
    </script>
</head>

<body>
    <div id="myDIV" class="input-field col s4">
    <?php
    $sql12 = "select * from fruitswhere total>0 && spent=1";
    $res1 = mysqli_query($conn, $sql12) or die("Error");
    $select = '<select id="selectid" name="name" onchange="myFunction()"><option value = "" disabled selected> Choose </option>';
    while($row1 = mysqli_fetch_assoc($res1)) {
        $emri = $row1['name'];
    // $select.='<option value = "'.$row1['name'].'">'.$row1['name '].'</option>';
        $select .= '<option id="my_option" value="'.$name.'">'.$name.'</option>';
    }
    $select .= '<option value="other">other</option>';
    $select .= '</select>';
    echo $select;
    ?>
    </div>

    <div class="input-field col s4">
    <?php
    $query2 = "SELECT total FROM fruits WHERE name='$name'";
    $res2 = mysqli_query($conn, $query2);
    while($row2=mysqli_fetch_assoc($res2)){
        $all = $row2['total'];
    }
    ?>
    <input name="total" type="number" min="1">
    </div>
</body>
</html>

最佳答案

您可以设置一个简单的脚本来响应请求。例如,您可以制作fruitCount.php:

<?php
include('db.php');

$sql = 'SELECT total '.
       'FROM fruits '.
       'WHERE name="'.mysqli_real_escape_string($_POST['name']).'"';
$result = mysqli_query($conn, $sql);
if ($result != NULL) {
    $row = mysqli_fetch_assoc($result);
    print($row['total']);
} else {
    print(0);
}
die();


然后在页面上,您可以使用jQuery设置一个click事件,该事件从该资源请求数据:

$('#selectid').change(function(){
        $.post('fruitCount.php',           // Server target for request
               { name: $(this).val() },    // POST payload
               function(resp){             // Handle response from server
                   $('#myDiv').html(resp); // Populate value to page
               });
    });


这种实现允许在事物在服务器端发生变化的环境中提供最新的值。如果仅在加载时需要该值,则可以在OPTION元素上设置data-count属性,并从中更新#myDiv:

$('#selectid').change(function(){
        $('#myDiv').html($(this).data('count'));
    });


如何实现它取决于您希望数据的实时程度。

09-11 19:11
查看更多