简体   繁体   中英

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

I need based on the user selected, to display data from that same user and everything that is in the database table.

When a user is selected through the dropdown menu and the button "search" is clicked, I need a table that pops up with all the data regarding that user.

This is the part where I get the users to show up in the drop down menu. But I'm a noob at coding so I have no idea where to go next, any help is appreciated.

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

Does it need to be on the same page or another one?

EDIT 1:

So, I gave you part of the solution for your problem. You'll still ned to change some value depending of your data. I wrote alot of comment in the Javascript code in the example, so read them carefully because I explain everything that I'm doing. Hope that will help you! If you still have some problem with the PHP script part, feel free to ask.


<?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: I'm using jQuery for change table value and making an HTTP request. You can see all information about this library here https://jquery.com/ and about the $.ajax() function here https://api.jquery.com/jquery.ajax/

To send an ajax request following a change even on the select menu you might consider using an ajax function which will send the selected option value to a backend script to process. The backend script does a db lookup and returns the data in some form ( json, html, xml ) which is then processed by the ajax callback function. The following is semi-pseudo code and is, of course, untested.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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