luna.romania
luna.romania

Reputation: 307

Update/Edit a form, so that it loads with selected option-values of SELECT from sql table

Here, I have already submitted my form values in sql table, with a multiple select, where I serialized selected values of <options> & inserted in SQL column : fldR.

Now, I am trying to UPDATE this form info, and trying to load this form.php, with fetched values from SQL table. I want to populate the MULTIPLE select, with fetched - selected option values.

PHP:

 $data = mysqli_fetch_object($result);
 $selected_values = unserialize($data->fldR);

Now what to do ?

HTML / PHP:

<select name="rtype[]" id="rtype" class="myselect" multiple="multiple" style="height:6em">
      <option value="hr">H1</option>
      <option value="fr">F1</option>
      <option value="rnr">R1</option>
</select>

Any creative ideas how this can be done?

Upvotes: 0

Views: 340

Answers (1)

Alok Patel
Alok Patel

Reputation: 8022

We can use in_array() to check if the value is in array or not, if yes execute certain code.

in_array() can accepts two arguments, first argument is the value you need to check and second parameter is array to be checked.

Now update your PHP/HTML code as below to select the values in SELECT box by default from databases.

Like this,

<select name="rtype[]" id="rtype" class="myselect" multiple="multiple" style="height:6em">
      <option value="hr" <?php if(in_array('hr',$selected_values)) { ?> selected="selected" <?php } ?>>H1</option>
      <option value="fr" <?php if(in_array('fr',$selected_values)) { ?> selected="selected" <?php } ?>>F1</option>
      <option value="rnr" <?php if(in_array('rnr',$selected_values)) { ?> selected="selected" <?php } ?>>R1</option>
</select>

http://php.net/manual/en/function.in-array.php

Upvotes: 0

Related Questions