簡體   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