利用数组值填充表单并通过表单访问数据库
Hey there! Let's break this down into simple, non-jQuery steps that are both efficient and easy to follow. I'll cover populating your dropdown, handling the selection, and fetching the corresponding data—all with vanilla JavaScript and clean PHP.
1. Simplify Your PHP Database Setup & Populate the Dropdown
First, let's clean up your database connection and directly generate the dropdown options from your Lname values (you don't even need to store them in a separate array unless you have another use for it). We'll use prepared statements to keep things secure too:
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "my_database"; // Create connection with proper error handling $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Fetch Lname values securely (replace 'your_table' with your actual table name) $stmt = $conn->prepare("SELECT Lname, id FROM your_table"); $stmt->execute(); $result = $stmt->get_result(); ?> <!-- Your form dropdown --> <select id="lnameSelect"> <option value="">Select a Last Name</option> <?php while ($row = $result->fetch_assoc()): ?> <option value="<?php echo htmlspecialchars($row['id']); ?>"> <?php echo htmlspecialchars($row['Lname']); ?> </option> <?php endwhile; ?> </select> <!-- Table to display the selected entry --> <table id="entryTable" border="1" style="display:none;"> <thead> <tr> <th>ID</th> <th>Last Name</th> <th>Email</th> <!-- Replace with your actual database fields --> <th>Phone</th> </tr> </thead> <tbody id="tableBody"></tbody> </table> <?php $stmt->close(); $conn->close(); ?>
Note: Replace your_table and the table columns with your actual database details. Using htmlspecialchars() prevents XSS attacks when outputting user data.
2. Vanilla JavaScript to Fetch & Display the Selected Entry
Since you don't know jQuery, we'll use the native fetch() API to get the data when the dropdown changes. First, create a separate PHP file (let's call it fetch_entry.php) to handle the database query for the selected entry:
fetch_entry.php
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "my_database"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die(json_encode(["error" => "Connection failed"])); } // Get the selected ID from the request if (isset($_GET['id'])) { $id = $_GET['id']; // Fetch full entry using prepared statement $stmt = $conn->prepare("SELECT * FROM your_table WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); $result = $stmt->get_result(); if ($row = $result->fetch_assoc()) { echo json_encode($row); } else { echo json_encode(["error" => "No entry found"]); } $stmt->close(); } else { echo json_encode(["error" => "No ID provided"]); } $conn->close(); ?>
Add this JavaScript to your main page
Put this right before the closing </body> tag:
document.getElementById('lnameSelect').addEventListener('change', function() { const selectedId = this.value; const table = document.getElementById('entryTable'); const tableBody = document.getElementById('tableBody'); if (!selectedId) { table.style.display = 'none'; return; } // Fetch the entry using native browser API fetch(`fetch_entry.php?id=${selectedId}`) .then(response => response.json()) .then(data => { if (data.error) { alert(data.error); table.style.display = 'none'; return; } // Clear existing table rows tableBody.innerHTML = ''; // Create a new row with the fetched data const row = document.createElement('tr'); row.innerHTML = ` <td>${data.id}</td> <td>${data.Lname}</td> <td>${data.email}</td> <!-- Match your database fields here --> <td>${data.phone}</td> `; tableBody.appendChild(row); // Show the table table.style.display = 'table'; }) .catch(error => { console.error('Error:', error); alert('Failed to fetch entry'); }); });
Why This Is a Simplified Approach
- No extra arrays: We directly generate dropdown options from the database query, skipping unnecessary array storage (unless you need that array for another task).
- Secure: Prepared statements prevent SQL injection, which is critical for safe database interactions.
- Vanilla JS only: No jQuery dependency—uses native browser APIs that work across all modern browsers.
- Clean separation: The
fetch_entry.phphandles database logic separately from your front-end code, making it easier to maintain and debug.
If you already have the Lname array for some specific reason, you can just loop through that array instead of the database result to generate the dropdown options—everything else in the solution stays exactly the same.
内容的提问来源于stack exchange,提问作者supamario44

