I am trying to remove as much code from within my html as possible without using a template framework and I am unsure why 'selected'
is not being returned to define 'selected'
for the options of a select box. $row_status
populates the options ok and $status
has a value assigned.
Am I way off on this?
<select id='status'>
<option>Please Select</option>
<?php while($row_status = mysqli_fetch_assoc($results_status)): ?>
<option <?php sel($row_status['list_value'],$status)?> > <?php echo $row_status['list_value'] ?> </option>
<?php endwhile; ?>
</select>
function sel($rs, $status){
if ($rs==$status){
return "selected";
}
}
You are only returning a value, not echoing it.
<?php echo sel(...); ?>
should work for you. You also might want to change your function to return an empty string in case the condition is not true.
function sel($rs, $status) {
return ($rs == $status) ? "selected" : "";
}
You can simplify your code by using sprintf()
and passing the conditions and values via its arguments:
while ($row_status = mysqli_fetch_assoc($results_status)) {
echo sprintf('<option%s>%s</option>',
$row_status['list_value'] == $status ? ' selected' : '',
htmlspecialchars($row_status['list_value'], ENT_QUOTES, 'UTF-8')
);
}
I've added the proper HTML escaping as well.