You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为PHP获取的员工列表添加JS/PHP姓名搜索筛选功能?

Hey there! I know that stuck feeling when you've been trying to add a feature for a week and can't find the right fit. Let's get that name search working for your employee list—here are two solid solutions, one using frontend JavaScript (no page reloads) and another using backend PHP (better for large datasets).

方案一:前端JavaScript实时搜索(无需刷新)

This is perfect if you don't have a huge number of employees—it filters the list you've already loaded on the client side, so it's fast and simple to implement.

You already have the input field set up with onkeyup="myFunction()", so you just need to add the JavaScript function. Here's how to modify your code:

First, add this script right before the closing </body> tag (or in a separate JS file):

function myFunction() {
  // Get the search input value, convert to lowercase for case-insensitive search
  let input = document.getElementById("myInput").value.toLowerCase();
  // Grab all employee list items
  let liItems = document.getElementById("myUL").getElementsByTagName("li");

  // Loop through each list item to check for matches
  for (let i = 0; i < liItems.length; i++) {
    // Extract the employee name from the .contacts-list-name span
    let name = liItems[i].querySelector(".contacts-list-name").textContent.toLowerCase();
    // Show/hide the item based on whether it matches the search term
    liItems[i].style.display = name.includes(input) ? "" : "none";
  }
}

Your existing HTML/PHP doesn't need any other changes—this function will automatically show/hide list items as the user types.

方案二:后端PHP搜索(适合大数据量)

If you have a lot of employees, loading all of them upfront isn't efficient. Instead, we'll let the database do the filtering, which is faster and uses less bandwidth. We can do this two ways: with a page refresh or AJAX (no refresh).

方式A:表单提交(页面刷新)

First, wrap your input in a form to send the search term to PHP:

<form method="GET" action="">
  <input type="text" id="myInput" name="search" placeholder="Search for names.." title="Search Name" value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
</form>
<ul id="myUL" class="contacts-list">
  <!-- Your existing PHP loop goes here, modified below -->
</ul>

Now update your PHP query to use the search term (critical: use PDO parameter binding to avoid SQL injection!):

<?php
$status = 1;
// Get the search term from the URL, default to empty string if not set
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';

// Prepare the SQL query with placeholders for safe input handling
$sql1 = $dbh->prepare("SELECT * FROM employee WHERE status = :status AND (fname LIKE :search OR lname LIKE :search)");

// Bind parameters: add % wildcards to match any part of the name
$searchParam = "%{$searchTerm}%";
$sql1->bindParam(':status', $status, PDO::PARAM_INT);
$sql1->bindParam(':search', $searchParam, PDO::PARAM_STR);

$sql1->execute();
if($sql1->rowCount() > 0) {
  while($row = $sql1->fetch(PDO::FETCH_ASSOC)){
    // Your existing HTML for each list item stays the same
?>
<li>
  <a href="messages.php?employee_id=<?php echo $row['employee_id']; ?>">
    <div class="contacts-list-info">
      <span class="contacts-list-name">
        <?php echo $row['fname']." ".$row['lname']; ?>
        <small class="contacts-list-date pull-right">
          <?php echo $row['status'] == '1' ? 'Online' : 'Offline'; ?>
        </small>
      </span>
      <span class="contacts-list-msg">
        <?php echo $row['role']; ?>
      </span>
    </div>
  </a>
</li>
<?php
  }
} else {
  // Show a message if no employees match the search
  echo "<li>No employees found matching your search.</li>";
}
?>

方式B:AJAX无刷新搜索(更流畅)

For a smoother user experience, we can use AJAX to send the search term to PHP without reloading the page. Here's how:

First, update your input to remove the onkeyup attribute (we'll use an event listener instead):

<input type="text" id="myInput" placeholder="Search for names.." title="Search Name">
<ul id="myUL" class="contacts-list">
  <!-- Initial list loads here, and we'll update it via AJAX -->
</ul>

Add this vanilla JavaScript code (no libraries needed):

document.getElementById("myInput").addEventListener("keyup", function() {
  let searchTerm = this.value.trim();
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "search-employees.php?search=" + encodeURIComponent(searchTerm), true);
  xhr.onload = function() {
    if (this.status === 200) {
      document.getElementById("myUL").innerHTML = this.responseText;
    }
  };
  xhr.send();
});

Now create a new file called search-employees.php with the PHP code that returns filtered list items (make sure to include your database connection here):

<?php
// Include your database connection file (same $dbh setup as your original code)
require_once 'your-db-connection-file.php';

$status = 1;
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';

$sql1 = $dbh->prepare("SELECT * FROM employee WHERE status = :status AND (fname LIKE :search OR lname LIKE :search)");
$searchParam = "%{$searchTerm}%";
$sql1->bindParam(':status', $status, PDO::PARAM_INT);
$sql1->bindParam(':search', $searchParam, PDO::PARAM_STR);
$sql1->execute();

if($sql1->rowCount() > 0) {
  while($row = $sql1->fetch(PDO::FETCH_ASSOC)){
?>
<li>
  <a href="messages.php?employee_id=<?php echo $row['employee_id']; ?>">
    <div class="contacts-list-info">
      <span class="contacts-list-name">
        <?php echo $row['fname']." ".$row['lname']; ?>
        <small class="contacts-list-date pull-right">
          <?php echo $row['status'] == '1' ? 'Online' : 'Offline'; ?>
        </small>
      </span>
      <span class="contacts-list-msg">
        <?php echo $row['role']; ?>
      </span>
    </div>
  </a>
</li>
<?php
  }
} else {
  echo "<li>No employees found matching your search.</li>";
}
?>

Quick Notes:

  • Frontend JS: Best for small datasets, instant feedback, no extra server calls after the initial page load.
  • Backend PHP: Better for large datasets, more secure (filtering happens server-side), and avoids loading unnecessary data.
  • Always use PDO parameter binding (like we did in the PHP examples) to prevent SQL injection—never concatenate user input directly into your SQL query!

内容的提问来源于stack exchange,提问作者Keerthi Kamarthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:59:53