如何通过PHP将MySQL筛选结果传入HTML指定div?
Hey there! Let's fix up your code to make it cleaner, more reliable, and easier to maintain. First, let's go over the key issues in your current implementation:
- Mixed database functions: You're using
mysqli_querybut thenmysql_fetch_assoc— these are from incompatible extensions! Stick withmysqli_*functions for consistency. - Unnecessary JS in PHP: You don't need to echo JavaScript from PHP to clear the container; this can be handled directly in your Ajax callback.
- Syntax errors: Your while loops have mismatched parentheses, and the quote escaping in your echoed JS is broken.
- Case mismatch: Your dropdown values are lowercase (
other,person) but your PHP checks for uppercase (Other,Person) — those will never match! - Inconsistent container IDs: Your Ajax targets
#responsecontainerbut your HTML has#container. - Inefficient JSON output: Encoding each row individually produces invalid JSON; collect all rows into an array first, then encode once.
Step 1: Clean Up the HTML
Just a small tweak to add a default selected state and keep IDs consistent:
<html> <body> <select name="FilterDoc" onchange="filterby(this);"> <option disabled selected>Filter By</option> <option value="document_type">Document Type</option> <option value="date">Date</option> <option value="hei">HEI</option> <option value="other">Other Govt.</option> <option value="person">Person</option> </select> <div class="panel-body" id="container"></div> </body> </html>
Step 2: Improve the Ajax/JavaScript
We'll clear the container immediately, handle loading states, and render data cleanly from a JSON response:
<script type="text/javascript"> function filterby(sel) { const filterValue = $(sel).val(); const $container = $("#container"); // Show loading state while fetching data $container.html('<p>Loading records...</p>'); $.ajax({ type: "POST", data: { FilterDoc: filterValue }, url: "filterdocu.php", dataType: "json", // Use JSON for structured data handling success: function(response) { if (response.success && response.data.length > 0) { // Build HTML from the returned data (customize this to your needs) let html = '<div class="panel panel-primary"><div class="panel-body"><ul>'; response.data.forEach(row => { html += `<li> <strong>Type:</strong> ${row.document_type} | <strong>Date:</strong> ${row.date_received} | <strong>Contact:</strong> ${row.contact_person} </li>`; }); html += '</ul></div></div>'; $container.html(html); } else { $container.html('<p>No matching records found.</p>'); } }, error: function(xhr, status, error) { $container.html(`<p>Error loading data: ${error}</p>`); console.error("Ajax request failed:", status, error); } }); } </script>
Step 3: Rewrite the PHP Logic
We'll use a lookup map to avoid repetitive if/else statements, fix database calls, and return valid JSON:
<?php // Ensure your mysqli connection ($conn) is properly initialized here header("Content-Type: application/json"); $response = [ "success" => false, "data" => [] ]; if (isset($_POST["FilterDoc"])) { $filter = $_POST["FilterDoc"]; // Map dropdown values to database columns and sort orders $filterMap = [ "document_type" => ["column" => "document_type", "order" => "ASC"], "date" => ["column" => "date_received", "order" => "DESC"], "hei" => ["column" => "hei", "order" => "ASC"], "other" => ["column" => "other_govt", "order" => "ASC"], "person" => ["column" => "contact_person", "order" => "ASC"] ]; if (isset($filterMap[$filter])) { $column = $filterMap[$filter]["column"]; $order = $filterMap[$filter]["order"]; // Safe query: we validate the column/order against our map to prevent SQL injection $query = "SELECT * FROM records ORDER BY `$column` $order"; $result = mysqli_query($conn, $query); if ($result) { while ($row = mysqli_fetch_assoc($result)) { $response["data"][] = $row; } $response["success"] = true; } else { $response["error"] = mysqli_error($conn); } } else { $response["error"] = "Invalid filter option selected"; } } else { $response["error"] = "No filter option provided"; } echo json_encode($response); ?>
Key Improvements Explained
- Lookup map: Replaces messy if/else chains with a clean, maintainable table — adding new filters is as simple as updating the map.
- Separation of concerns: Frontend handles rendering, backend handles data retrieval, making code easier to debug and modify.
- SQL safety: By validating user input against our allowed list, we eliminate SQL injection risks.
- Error handling: Both frontend and backend handle failures gracefully, with clear feedback for debugging.
内容的提问来源于stack exchange,提问作者Abraham
相关产品推荐
相关产品推荐

