PHP实现数据库取值绑定到<select>下拉框问题求解
The core issue here is that <select> elements don’t use the value attribute to set their default selected state—instead, you need to apply the selected attribute directly to the specific <option> that matches your database value. Here’s how to fix this properly:
Step 1: Capture the Database Value
First, store the cleaned value from your database result in a variable for easy reuse:
$selectedPlateType = remove_junk($vehicle_inv['number_plate_desc']);
Step 2: Update the Dropdown with Conditional Selection
Modify each <option> to check if its value matches the stored database value. If it does, add the selected attribute to that option:
<select class="custom-select form-control" id="numberPlateType" name="numberPlateType"> <option value="1" <?php echo ($selectedPlateType === '1') ? 'selected' : ''; ?>>Both Original</option> <option value="2" <?php echo ($selectedPlateType === '2') ? 'selected' : ''; ?>>One Original, One Duplicate</option> <option value="3" <?php echo ($selectedPlateType === '3') ? 'selected' : ''; ?>>Both Duplicate</option> </select>
Why This Works
- We removed the hardcoded
selectedfrom the first option, which was overriding your database value. - For each option, a ternary operator checks if its value matches
$selectedPlateType. If there’s a match, it outputsselected, telling the browser to select that option by default.
Bonus: Security Improvement
Your current query is vulnerable to SQL injection because you’re directly concatenating $veh_id into the query string. Switch to prepared statements to fix this:
$vehicleQuery = "SELECT * FROM vehicle_purchased vp WHERE vp.vehicle_id = ?"; $stmt = $db->prepare($vehicleQuery); $stmt->bind_param("i", $veh_id); // Use "s" instead of "i" if $veh_id is a string $stmt->execute(); $vehicle = $stmt->get_result(); $vehicle_inv = $vehicle->fetch_assoc();
This ensures malicious input can’t manipulate your database query.
内容的提问来源于stack exchange,提问作者Ahmed Siddiqui

