繁体   English   中英

如何根据下拉菜单上的选定选项在表格上显示数据?

[英]How can I display data on a table based on the selected option on the dropdown menu?

我需要根据所选用户显示来自同一用户的数据以及数据库表中的所有内容。

当通过下拉菜单选择用户并单击“搜索”按钮时,我需要一个表格来弹出有关该用户的所有数据。

这是我让用户显示在下拉菜单中的部分。 但我是编码的菜鸟,所以我不知道下一步该去哪里,任何帮助表示赞赏。

<?php
session_start();
require 'includes/dbh.inc.php';
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="css/footer.css">
    <title>Document</title>
</head>
<body>

<div class="container h-100">
    <div class="row h-100 justify-content-center align-items-center">
        <form method="post" action="includes/shifts.inc.php" class="col-10">
            <div class="form-group text-center">
                <br>
                <h1 class="h3 mb-3 text-center  font-weight-normal">Create new shift</h1>

                <label for="form">Name</label>
                <select name="uid" class="form-control" required autofocus>
                  <?php
                  $res=mysqli_query($conn, "SELECT * FROM users");
                  while($row=mysqli_fetch_array($res))
                  {
                    ?>
                      <option name="uid"><?php echo $row["uidUsers"]; ?></option>
                    <?php
                  }
                  ?>
                </select>
            </div>
        </form>
    </div>
</div>

<button class="btn btn-lg btn-primary btn-block" name="search" type="submit">Search</button>

</body>
</html>

它需要在同一页上还是在另一页上?

编辑 1:

因此,我为您提供了部分问题的解决方案。 您仍然需要根据您的数据更改某些值。 我在示例中的 Javascript 代码中写了很多注释,所以请仔细阅读它们,因为我解释了我正在做的一切。 希望能帮到你! 如果您对 PHP 脚本部分仍有一些问题,请随时提问。


<?php
session_start();
require 'includes/dbh.inc.php';
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="css/footer.css">
    <title>Document</title>
</head>
<body>

<div class="container h-100">
    <div class="row h-100 justify-content-center align-items-center">
        <form method="post" action="includes/shifts.inc.php" class="col-10">
            <div class="form-group text-center">
                <br>
                <h1 class="h3 mb-3 text-center  font-weight-normal">Create new shift</h1>

                <label for="form">Name</label>
                <select name="uid" class="form-control" required autofocus>
                  <?php
                  $res=mysqli_query($conn, "SELECT * FROM users");
                  while($row=mysqli_fetch_array($res)): ?> <!-- Use adapted version of while for easier reading in HTML -->
                      <option value="<?php echo $row["id_of_user"]; ?>"><?php echo $row["uidUsers"]; ?></option> <!-- Here, you don't need to 'name' your option, you only need to give them value and id (optionnal). You need to change $row["id_of_user"] for the first of the ID of user -->
                  <?php endwhile; ?>
                </select>
            </div>
        </form>
    </div>
</div>

<button class="btn btn-lg btn-primary btn-block" name="search" type="submit">Search</button>

<!-- 

THIS IS THE NEW TABLE WHERE WE'LL PLACE OUR DATA

 -->
<table id="userTable" style="display:none">
    <tbody>
        <tr>
            <th>First name</th>
            <td id="firstName"></td>
        </tr>
        <tr>
            <th>Last name</th>
            <td id="lastName"></td>
        </tr>
        <tr>
            <th>Birth date</th>
            <td id="birthDate"></td>
        </tr>
    </tbody>
</table>

</body>
</html>

<script>

// So first of all, we'll create a listener to capture when the user click on an <option>
$("select[name=uid] option").on('click', function() {

    // Get the value of the clicked option (suposed to be the ID of the user)
    let id = $(this).attr("value");

    // Let's make an AJAX call to get the user ID
    $.ajax({

        // Instead of "url", you'll put the url path of the script
        // you created to send the information back to this request
        url: "url",
        
        // This option is where you pass the value you want to send to the PHP script
        // Here we'll send the id of the user we want info from
        data: {
            "id": id
        },

        // This option is to make our life easier because it will automaticly decode
        // the data the script is sending us from JSON type
        dataType: 'json',

        // This option is a function called when the request is a success
        success: function (response) {
            
            /*

            For the purpose of the demonstration, the script will be returning
            the first name, the last name and the birth date of the user
            you selected with the select.

            So, the `response` variable (right above), contain the 3 value
            as a JSON. Because of the 'dataType' option, this is no longer a JSON,
            but a Javascript array now. So we'll get each value this way:
                response.firstName
                response.lastName
                response.birthDate

            This way, we'll be able to put those value in the table. Since
            the table is hidden, we'll display it with this jQuery function:
                .show()

            And we'll put the value in the first with the following lines:

            */

            // Grab the value from the request
            let firstName = response.firstName;
            let lastName = response.lastName;
            let birthDate = response.birthDate;

            // Put them in the table
            $("#firstName").val(firstName);
            $("#lastName").val(lastName);
            $("#birthDate").val(birthDate);
            
            // Show the table
            $("#userTable").show();
            
        },
    });
})
</script>

PS:我使用 jQuery 来更改表值并发出 HTTP 请求。 您可以在此处查看有关此库的所有信息https://jquery.com/以及有关 $.ajax() 函数的所有信息https://api.jquery.com/jquery.ajax/

要在选择菜单上发生更改后发送 ajax 请求,您可能会考虑使用 ajax 函数,该函数会将选定的选项值发送到后端脚本进行处理。 后端脚本执行数据库查找并以某种形式( json, html, xml )返回数据,然后由 ajax 回调函数处理。 以下是半伪代码,当然未经测试。

<?php
    # /some/script.php

    require 'includes/dbh.inc.php';

    $sql='select * from users where uid=?';
    $stmt=$conn->prepare( $sql );
    $stmt->bind_param( 's', $uid );


    $uid=$_POST['uid'];
    $res=$stmt->execute();

    $data=$stmt->get_result();
    $stmt->close();
    $conn->close();

    exit( json_encode( $data ) );

?>







<select name="uid" class="form-control" required autofocus>
    ......
</select>




<script>

    let ajax_target='/path/to/some/script.php';

    document.querySelector('select[name="uid"]').addEventListener('change',function(e){
        let xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if( this.status==200 && this.readyState==4 ){
                    ( e )=>{
                        alert( e.response )
                    }
                }
            }
            xhr.open( 'POST', ajax_target, true );
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.send( 'uid='+this.value );
    });
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM