nicemanda
nicemanda

Reputation: 91

Require help to show selected list items in php/html form based on existing MySQL data

Any help would be greatly appreciated!!

I am building a php form to update a MySQL database linked to my website.

Part of my form includes list fields where the user can hold ctrl to select multiple values and these are then passed into one MySQL field as comma separated values. See below for three real examples of the data:

3014

3014,3015,3026

3026,3028

The form is updating my database as required, however when the user goes back in to the form to do another update the multiple values they chose aren't pre-selected.

Can anyone help me to figure out why $row_editme['NewsTypeID'] is the field containing the string of values. The field type is a SET.

<td nowrap="nowrap" align="right">NewsTypeID:</td>
<td>
  <select name="NewsTypeID[]" size="4" multiple="multiple">
  <?php 
    do {  
  ?>
     <option value="<?php echo $row_types['id']?>" <?php if (!(strcmp($row_types['id'], htmlentities($row_editme['NewsTypeID'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>><?php echo $row_types['name']?></option>
  <?php } while ($row_types = mysql_fetch_assoc($types)); ?>
      </select>
</td>

Upvotes: 1

Views: 713

Answers (2)

Deepak
Deepak

Reputation: 6812

Try something like this,

<select name="NewsTypeID[]" size="4" multiple="multiple">
  <?php 
  do {  
    $selected = htmlentities($row_editme['NewsTypeID'], ENT_COMPAT, 'utf-8');
    $selected_arr = explode(",",$selected);
  ?>
   <option value="<?php echo $row_types['id']?>" <?php if (in_array($row_types['id'],$selected_arr)) {echo "selected";} ?>>
      <?php echo $row_types['name']?>
   </option>
  <?php } while ($row_types = mysql_fetch_assoc($types)); ?>
</select>

Upvotes: 1

simplecoder
simplecoder

Reputation: 203

I think it is not supposed to be selected.

Can you try checked?

<input type="checkbox" <?php /*if condition is met here, then*/ echo "checked='checked'" ?> />

It will pre-select all the values the user selected.

Upvotes: 0

Related Questions