-2

I am trying to find a clear answer for populating a select option drop down menu with a value from a database. I have found various answers including this one which I thought was what I needed but turned out to not be the case.

selected value get from db into dropdown select box option using php mysql error

As described in the previous post my question looks like so. I have a form that is populated with all the database values of a current listing. I can get everything to echo correctly except what the user previously selected under status.

A snippet of my form is as follows. MLS # echos back from the saved variable $listingMLS just fine and populates the form perfectly however when I echo $listingStatus which returns the correct value of the current listing it does not update the selected option.

I am sure there is something I am missing and will provide any further descriptions needed. I hope I conveyed this clearly.

<div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-8">
MLS #
<input type="text" maxlength="100" class="form-control" name="listingMLS" value="<?php echo $listingMLS; ?>">
    </div>
    <div class="col-md-2"></div>
</div>

<br>

<div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-8">
Status
<select class='form-control' name='listingStatus' value="<?php echo $listingStatus; ?>">
<option value='0' selected>Active</option>
<option value='1' selected>Price Reduced</option>
<option value='2' selected>Sold</option>
<option value='3' selected>Archived</option>
</select>
    </div>
    <div class="col-md-2"></div>
</div>

Thank you for any help.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
BlueLycan
  • 31
  • 8

1 Answers1

0

value is not a valid attribute for <select> element. See docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

You should compare $listingStatus inside the loop and then print selected if matched. Something like:

<select class='form-control' name='listingStatus'>
<?php
   foreach($DBListing as $listing):
      echo '<option value="'. $listing['status'] .'" '.
         (($listing['status'] == $listingStatus)?'selected="selected"':'')
      .'>'. $listing['title'] .'</option>';
   endforeach;
?>
</select>
caiovisk
  • 3,667
  • 1
  • 12
  • 18