如何在PHP mysqli用户列表中排除自身IP地址条目
Hey there! To exclude the user entry matching your own IP address from the list, you’ve got two solid options—filtering directly in the SQL query (the more efficient choice) or skipping the entry while looping through results. Let’s walk through both, plus fix a couple of security gaps in your existing code along the way.
Approach 1: Filter in SQL (Recommended)
This method is better because it cuts down on unnecessary data pulled from the database. Since you already have the current logged-in user’s data stored in $userRow, we can use their IP to exclude matching entries right in the user list query. We’ll also use prepared statements to avoid SQL injection (your current code has some injection risks we should address).
Replace your existing user list query code:
$user_list_result = $DBcon->query("select * from users order by username ASC limit 100");
With this secure, filtered version:
// Grab the current logged-in user's IP address $current_user_ip = $userRow['ip']; // Prepare a parameterized query to exclude the current IP $stmt = $DBcon->prepare("SELECT * FROM users WHERE ip != ? ORDER BY username ASC LIMIT 100"); $stmt->bind_param("s", $current_user_ip); // "s" tells MySQL we're passing a string $stmt->execute(); $user_list_result = $stmt->get_result();
Approach 2: Skip Entries in the Loop
If you’d rather keep the original query (though it’s less efficient), you can add a quick check inside the while loop to skip any entry that matches your IP:
<?php while($UserlistRow = $user_list_result->fetch_array()) { // Skip the row if its IP matches the current user's IP if($UserlistRow['ip'] === $userRow['ip']) { continue; } // Your existing table row output code goes here echo " <tr> <td>$UserlistRow[user_id]</td> <td><a href=user_profile.php?user=$UserlistRow[username]>$UserlistRow[username]</a></td></center>"; // ... rest of your table cell content } ?>
Quick Security Reminder
Your current code uses string interpolation for queries (like WHERE username='$session'), which leaves you open to SQL injection. You should update that query to use prepared statements too, just like the example above:
$session = $_SESSION['usr_name']; $stmt = $DBcon->prepare("SELECT * FROM users WHERE username = ?"); $stmt->bind_param("s", $session); $stmt->execute(); $query_result = $stmt->get_result(); $userRow = $query_result->fetch_array();
This small change will protect your database from malicious input.
内容的提问来源于stack exchange,提问作者Patrick Verkennis

