简体   繁体   English

选择下拉列表时,生成更多的MYSQL数据库结果

[英]Generating more MYSQL database results when a dropdown list is selected

hope you can help 希望你能帮忙

I want to have a drop down list that searches my mysql database and shows the first and last names of the users. 我想要一个下拉列表,该列表搜索我的mysql数据库并显示用户的名字和姓氏。 You can then select any of the names and it will generate the rest of the membership details (ie date signed up, last logged in etc). 然后,您可以选择任何名称,它将生成其余的成员资格详细信息(即注册日期,上次登录等)。

I have got the dropdown list working fine, but my problem comes with the next step of generating the rest of the details. 我的下拉列表运行正常,但是我的问题来自生成其余详细信息的下一步。 With my below code it just shows the details of the last user who signed up and does not change when I change the name in the drop down menu. 使用下面的代码,它仅显示最后一个注册用户的详细信息,当我在下拉菜单中更改名称时,该用户不会更改。

I'm pretty sure I need Javascript to help get this working but as I am a beginner to PHP/MYSQL any advise toward the right direction for me would be great. 我很确定我需要Javascript来帮助实现此功能,但是由于我是PHP / MYSQL的初学者,因此对我来说正确的方向提供任何建议都非常有用。 Thanks 谢谢

This is the code which searches my database and puts the first and last name in to a drop down list 这是搜索我的数据库并将名字和姓氏放入下拉列表的代码

$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px">';
while ($row = mysqli_fetch_assoc($query)){
    $firstname = $row['first_name'];
    $lastname = $row['last_name'];
    echo'<option>' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';

Again the above code works fine, but the below code is what I am having difficulty with 上面的代码再次正常工作,但是下面的代码是我遇到的困难

$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
    echo "ID: " . " " . $row[0] . "<br>" . 
        "Name: " . $row[1] . " " . $row[2] . "<br>" . 
        "Company: " . $row[3] . "<br> " . 
        "Email: " .$row[4] . "<br> " . 
        "Date of registration: " . $row[6] . "<br> " . 
        "Last login:  " .$row[7] . "<br>" . 
        "Admin/User: " .$row[8] . "<p>";
}

if you don't want to use AJAX to dynamically load the content, you need a form to submit the data, your problem is that after your first loop, $firstname is the last user loaded into the , to make your code work, you need a form. 如果您不想使用AJAX动态加载内容,则需要一个表单来提交数据,您的问题是,在第一个循环之后,$ firstname是加载到中的最后一个用户,以使您的代码正常工作,需要表格。

just put the select in a form and add a button 只需将选择内容放入表单并添加一个按钮

    <form action="mypage.php" method="get">
    <select name="name" style="width: 400px">
    <?php
    $sql = "SELECT first_name,last_name FROM registration_tbl";
    $query = mysqli_query($dbc, $sql);
    while ($row = mysqli_fetch_assoc($query)){
        $firstname = $row['first_name'];
        $lastname = $row['last_name'];
        echo'<option>' . $firstname . " " . $lastname . '</option>';
    }
    ?>

</select>
<input type="submit" value="Load User Data">
</form>

then in mypage.php you need to check if the form is submitted, and show the user details. 然后在mypage.php中,您需要检查表单是否已提交,并显示用户详细信息。

<?php
if(isset($_GET["name"]))  {
   //this form is posted, show user details
   //$firstname = $_GET["name"]; <--- SQL Injection enabled here!!
   $firstname = mysqli_real_escape_string($_GET["name"]); // please try to avoid SQL injection!
   //your code continues here
   $sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
   $query = mysqli_query($dbc, $sql);
   while($row = mysqli_fetch_array($query)){
      echo "ID: " . " " . $row[0] . "<br>" . 
        "Name: " . $row[1] . " " . $row[2] . "<br>" . 
        "Company: " . $row[3] . "<br> " . 
        "Email: " .$row[4] . "<br> " . 
        "Date of registration: " . $row[6] . "<br> " . 
        "Last login:  " .$row[7] . "<br>" . 
        "Admin/User: " .$row[8] . "<p>";
   }

} }

last note, if you don't want the username to appear in the querystring, change form action to post, and get variable using $_POST["name"] 最后一点,如果您不希望用户名出现在查询字符串中,请将表单操作更改为post,然后使用$ _POST [“ name”]获取变量

EDIT: if you want the form to autopost using javascript then add this to ur select definition: 编辑:如果您希望表单使用javascript自动发布,则将其添加到您的选择定义中:

<select name="name" style="width: 400px" onchange="this.form.submit()">

but bear in mind that a lot of users block javascript, thus this will not work. 但请记住,许多用户都阻止了javascript,因此这是行不通的。

The best way would be to use AJAX to get the data of the other script. 最好的方法是使用AJAX获取其他脚本的数据。 However, another (far less elegant and efficient) way of doing it is while you're looping through the names to put into the select. 但是,另一种方法(远远不够优雅和有效)是当您遍历要放入选择项的名称时。 You can also be using the names to get the info for that name and put it into an array (but don't echo it) until you need it. 您还可以使用名称来获取该名称的信息,并将其放入数组中(但不要回显它),直到需要它为止。

Use this code from where user will select the name 使用此代码,用户将在其中选择名称

<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function()
{

$(".listdata").change(function()
{
var dataString = 'listdata='+ $(this).val();
$.ajax
({
type: "POST",
url: "alldata",
data: dataString,
cache: false,
success: function(html)
{
$(".alldata").html(html);
} 
});

});
});
</script>

<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px" class="listdata">';
while ($row = mysqli_fetch_assoc($query)){
    $firstname = $row['first_name'];
    $lastname = $row['last_name'];
    echo'<option value="'.$firstname.'">' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
?>
<div class="alldata">
    <!--here your all data will come-->

</div>
<br/><br/>

Crate one more and give the name alldata.php And use the below code on that page 再建立一个箱子,并命名为alldata.php,并在该页面上使用以下代码

<?php
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
    echo "ID: " . " " . $row[0] . "<br>" . 
        "Name: " . $row[1] . " " . $row[2] . "<br>" . 
        "Company: " . $row[3] . "<br> " . 
        "Email: " .$row[4] . "<br> " . 
        "Date of registration: " . $row[6] . "<br> " . 
        "Last login:  " .$row[7] . "<br>" . 
        "Admin/User: " .$row[8] . "<p>";
}
?>

Just to complete your options, here you have a full but basic AJAX implementation (using jQuery): 只是为了完成您的选择,这里您有完整但基本的AJAX实现 (使用jQuery):

File select.php (javascript part at the bottom of the file): 文件select.php (文件底部的javascript部分):

<?php
  // Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
  // Retrieve list of people... (notice I've added id column!)
  $sql = "SELECT id, first_name, last_name FROM registration_tbl";
  $query = mysqli_query($dbc, $sql);
  $people = [];
  while ($row = mysqli_fetch_assoc($query)){
    $people[$row['id']] = $row['first_name'] . " " . $row['last_name'];
  }
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>List of people</title>
  <style type="text/css">
    .error {
        color: red;
        box-shadow: 0px 0px 15px 0px rgba(247, 17, 40, 0.44);
    }
    #person-info {
        padding: 10px;
        margin-top: 1em;
    }
  </style>
</head>
<body>
  <h2>People list</h2>
    <label for="person">Please select one person</label> 
    <select name="person" id="people-selection">
        <option value="-1"></option>

    <?php foreach ($people as $person_id => $person_name): ?>
        <option value="<?php echo $person_id ?>"><?php echo $person_name ?></option>
    <?php endforeach; ?>

    </select>
  <div id="person-info"><!-- here we will put person info using AJAX request --></div>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
        // We bind our AJAX handler to the onChange event of the select element
        $("#people-selection").on('change', function(e) {
            if ($(this).val() != -1) {  // If we did select some value
                $.ajax({
                    type: "POST",
                    url : "/get_people_info.php",
                    data: { id: $(this).val() },
                })
                  .done(function(data) {
                    $("#person-info")
                        .removeClass("error")  // we don't need the error class here, it's a success response
                        .html(data);
                  })
                  .fail(function(jqXHR, textStatus, errorThrown) {
                    $("#person-info")
                        .addClass("error")      // in order to add some UI for the user
                        .html("Something went wrong!<br><blockquote>" + errorThrown + "</blockquote>");
                  });
            }
            else {
                $("#person-info")
                    .removeClass("error")
                    .html("");
            }
        })
    });
  </script>
</body>
</html>

And then get_people_info.php 然后get_people_info.php

<?php

if ($_SERVER['REQUEST_METHOD'] !== "POST") {
    header('HTTP/1.0 400 Bad request');
    die("Only POST request accedpted!");
}

if (!isset($_POST['id'])) {
    header('HTTP/1.0 400 Bad request');
    die("id parameter is mandatory!");
}

$id = (int) $_POST['id'];

// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
$sql = "SELECT * FROM registration_tbl WHERE id = ". $id .";";
$query = mysqli_query($dbc, $sql);

if ($row = mysqli_fetch_array($query)){
    echo "<p>ID: " . " " . $row[0] . "<br>" . 
         "Name: " . $row[1] . " " . $row[2] . "<br>" . 
         "Company: " . $row[3] . "<br> " . 
         "Email: " .$row[4] . "<br> " . 
         "Date of registration: " . $row[6] . "<br> " . 
         "Last login:  " .$row[7] . "<br>" . 
         "Admin/User: "  .$row[8] . "</p>";
}
else {
    echo "Person not found!";
}

Let me give you some further reading (you said you were new to PHP, I asume the whole web development): 让我进一步阅读(您说您是PHP的新手,我假设是整个Web开发):

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

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