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

时间:2019-07-03 18:29:54

标签: php sql

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

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

这是使用户显示在下拉菜单中的部分。 但是我对编码不熟悉,所以我不知道下一步该怎么做,我们将不胜感激。

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

2 个答案:

答案 0 :(得分:1)

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

编辑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/处查看有关此库的所有信息,并在https://api.jquery.com/jquery.ajax/处查看有关$ .ajax()函数的所有信息。

答案 1 :(得分:1)

要在更改后甚至在选择菜单上发送ajax请求,您可能会考虑使用ajax函数,该函数会将选定的选项值发送到后端脚本进行处理。后端脚本执行db查找,并以某种形式(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>