PHP用户信息编辑:如何实现管理面板中用户操作按钮功能?
Hey there! Let's get those refresh and action buttons (the sync and gavel icons) working properly for your user admin panel. Here's a step-by-step breakdown to make them functional:
1. Add User Identification to Your Buttons
First, your buttons need to know exactly which user they're acting on. Assuming your users table has a unique user_id field (you should have one for this exact use case), modify your PHP code to include this ID in each button using a data-* attribute, and add classes to target them easily with JavaScript:
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['hwid']) . "</td> <td> <a href='#' class='action-btn refresh-btn' data-user-id='" . $row['user_id'] . "'><i class='fas fa-sync'></i></a> <a href='#' class='action-btn ban-btn' data-user-id='" . $row['user_id'] . "'><i class='fas fa-gavel'></i></a> </td></tr>";
Note: I added htmlspecialchars() to prevent XSS attacks—always sanitize user data when outputting to HTML!
2. Add Frontend JavaScript to Handle Clicks
Next, write some JavaScript to intercept button clicks, stop the default # page jump, and send a request to your backend to perform the action. You can add this script at the bottom of your HTML page (or in a separate JS file):
// Handle refresh button clicks (e.g., reset HWID) document.querySelectorAll('.refresh-btn').forEach(button => { button.addEventListener('click', function(e) { e.preventDefault(); // Stop the default link behavior const userId = this.dataset.userId; // Send request to backend to refresh the user's HWID fetch('refresh-user.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `user_id=${userId}` }) .then(response => response.json()) .then(data => { if (data.success) { alert('User HWID refreshed successfully!'); // Optional: Update the HWID column without reloading the page this.closest('tr').querySelector('td:nth-child(2)').textContent = 'Reset'; } else { alert('Failed to refresh user: ' + (data.error || 'Unknown error')); } }) .catch(error => console.error('Error refreshing user:', error)); }); }); // Handle ban/action button clicks document.querySelectorAll('.ban-btn').forEach(button => { button.addEventListener('click', function(e) { e.preventDefault(); const userId = this.dataset.userId; // Confirm action with the admin to avoid mistakes if (!confirm('Are you sure you want to take action against this user?')) { return; } // Send request to backend to perform the action fetch('ban-user.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `user_id=${userId}` }) .then(response => response.json()) .then(data => { if (data.success) { alert('User action completed successfully!'); // Optional: Remove the user row from the table immediately this.closest('tr').remove(); } else { alert('Failed to perform action: ' + (data.error || 'Unknown error')); } }) .catch(error => console.error('Error performing user action:', error)); }); });
3. Create Backend Scripts to Process Actions
Now you need two simple PHP scripts to handle the actual database operations. Make sure to use secure practices to avoid SQL injection!
refresh-user.php (Handles HWID Refresh)
<?php // Connect to your database (use your existing connection code) $conn = mysqli_connect('localhost', 'your_db_user', 'your_db_password', 'your_db_name'); // Check database connection if (!$conn) { die(json_encode(['success' => false, 'error' => 'Database connection failed'])); } // Validate user ID input if (!isset($_POST['user_id'])) { echo json_encode(['success' => false, 'error' => 'User ID not provided']); exit; } $userId = (int)$_POST['user_id']; // Cast to integer to prevent injection // Prepare and execute safe update query $stmt = mysqli_prepare($conn, "UPDATE users SET hwid = NULL WHERE user_id = ?"); mysqli_stmt_bind_param($stmt, "i", $userId); mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) > 0) { echo json_encode(['success' => true]); } else { echo json_encode(['success' => false, 'error' => 'No user found or no changes made']); } // Cleanup resources mysqli_stmt_close($stmt); mysqli_close($conn); ?>
ban-user.php (Handles User Ban/Action)
<?php // Connect to your database $conn = mysqli_connect('localhost', 'your_db_user', 'your_db_password', 'your_db_name'); if (!$conn) { die(json_encode(['success' => false, 'error' => 'Database connection failed'])); } if (!isset($_POST['user_id'])) { echo json_encode(['success' => false, 'error' => 'User ID not provided']); exit; } $userId = (int)$_POST['user_id']; // Example: Update user status to banned (adjust query to match your schema) $stmt = mysqli_prepare($conn, "UPDATE users SET is_banned = 1 WHERE user_id = ?"); mysqli_stmt_bind_param($stmt, "i", $userId); mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) > 0) { echo json_encode(['success' => true]); } else { echo json_encode(['success' => false, 'error' => 'No user found or no changes made']); } mysqli_stmt_close($stmt); mysqli_close($conn); ?>
Final Notes
- Adjust the database queries in the backend scripts to match your actual table schema (e.g., if you don't have an
is_bannedcolumn, modify the query to fit your intended action). - For better UX, replace
alert()with a more polished notification system (like toast messages) if you want. - Always validate and sanitize all input to keep your admin panel secure!
内容的提问来源于stack exchange,提问作者Sebastian Skov Nielsen

