Search code examples
phpselectselected

Trouble getting selected=selected to behave as expected when it's echo'd in php


This code should echo selected=selected to the relevant options, but it's not showing the selected value as highlighted, or showing selected=selected in the source code.

<?php   
try {  
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");  
$stmt->bindValue(':user_id', $user_id); 
$stmt->execute();
}catch(PDOException $e) {echo $e->getMessage();}
$row = $stmt->fetch();
?>
<select name="gift_privacy">
<option value="Standard" <?php if($row['gift_privacy']=='Standard') echo "selected='selected'"; ?>>Standard</option>
<option value="Gift ID Req" <?php if($row['gift_privacy']=='Gift_ID_Req') echo "selected='selected'"; ?>>Require program ID</option>
<option value="Not Enrolled" <?php if($row['gift_privacy']=='Not_Enrolled') echo     </select>

The result of var_dump($row);:

["gift_privacy"]=> string(12) "Not Enrolled"

The source code

<select name="gift_privacy" style="width:12em;">
<option value="Standard" >Standard</option>
<option value="Gift ID Req" >Require program ID</option>
<option value="Not Enrolled" >Do not enroll</option>
</select>

Solution

  • Your condition is:

    if($row['gift_privacy']=='Not_Enrolled')
    

    but your string is "Not Enrolled" (no underscore). Either change the condition and remove the underscore, or change the value you're returning to have an underscore.