如何在数据库无姓名匹配时为现有代码添加错误提示?
Hey Jan, let's get that missing feedback sorted out! The fix is pretty straightforward—we just need to check if our database query returns any matching results, and if not, display your custom message. Here's how to do it, depending on your setup:
Server-Side (PHP Example)
First, assuming you're using PHP to handle the database query (super common for this kind of task), here's how to adjust your code:
Before (no feedback on no matches):
<?php // Existing code (note: this has SQL injection risks!) $input = $_POST['user_input']; $query = "SELECT Vorname, Nachname FROM users WHERE Vorname LIKE '%$input%' OR Nachname LIKE '%$input%'"; $result = mysqli_query($conn, $query); while ($row = mysqli_fetch_assoc($result)) { echo "<p>" . $row['Vorname'] . " " . $row['Nachname'] . "</p>"; } ?>
After (with no-match feedback):
<?php // Secure version with prepared statements (always use these to prevent SQL injection!) $input = $_POST['user_input']; $conn = mysqli_connect("your_host", "your_user", "your_pass", "your_db"); // Prepare the query to avoid SQL injection $query = "SELECT Vorname, Nachname FROM users WHERE Vorname LIKE ? OR Nachname LIKE ?"; $stmt = mysqli_prepare($conn, $query); $searchTerm = "%$input%"; // Wrap input in wildcards for partial matches mysqli_stmt_bind_param($stmt, "ss", $searchTerm, $searchTerm); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); // Check if we have any matching rows if (mysqli_num_rows($result) > 0) { // Loop through and display matches while ($row = mysqli_fetch_assoc($result)) { // Use htmlspecialchars to prevent XSS attacks echo "<p>" . htmlspecialchars($row['Vorname']) . " " . htmlspecialchars($row['Nachname']) . "</p>"; } } else { // No matches? Show your custom message echo "<p style='color: #dc3545;'>Sorry, but none of your letters match with the Names in the database</p>"; } // Clean up resources mysqli_stmt_close($stmt); mysqli_close($conn); ?>
Key Changes Here:
- Added a result check:
mysqli_num_rows($result)tells us how many matches we found. If it's 0, we trigger the error message. - Secure query with prepared statements: I swapped out the old query for a prepared statement to protect against SQL injection—this is non-negotiable for user input!
- XSS protection: Used
htmlspecialchars()when outputting user data to prevent cross-site scripting attacks. - Styled the message: Added inline CSS to make the error stand out (you can replace this with a CSS class for cleaner code).
If You're Using AJAX (Frontend Handling)
If you're loading results asynchronously with JavaScript, you'll need to check the response from the server and display the message on the frontend:
// Vanilla JS example document.getElementById('search-form').addEventListener('submit', function(e) { e.preventDefault(); const input = document.getElementById('user-input').value; const resultsContainer = document.getElementById('results'); fetch('your-search-script.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `user_input=${encodeURIComponent(input)}` }) .then(response => response.text()) .then(data => { if (data.trim() === '') { // No matches returned from server resultsContainer.innerHTML = "<p class='error-message'>Sorry, but none of your letters match with the Names in the database</p>"; } else { // Display the matching results resultsContainer.innerHTML = data; } }); });
Quick CSS for the Error Message
Add this to your stylesheet to make the message look polished:
.error-message { color: #dc3545; /* Bootstrap danger red, adjust as needed */ padding: 1rem; border: 1px solid #f5c6cb; border-radius: 0.25rem; background-color: #f8d7da; }
The core idea is simple: always check if your query returns results, and handle the "no results" case explicitly. That way, users never see a blank page when their search doesn't match anything!
内容的提问来源于stack exchange,提问作者Jan Nick

