CallHimX
CallHimX

Reputation: 55

Show Data from Database in a multiple Dropdown using PHP

I'm using Chosen.js to show multi select dropdown menus in my forms. All these selected data by a user goes to a mysql database in a single string separated by a ";". So far, so good.

Now my problem is, I want to give my users a edit form, where they can edit all there given data. So I have to read out the data from the database and shown this up on the form. But what is the right way for a multi select dropdown menu?

<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>

Data saved in Database like: "21;22;23".

I'm really stuck at this...

Upvotes: 3

Views: 863

Answers (2)

syed suleman
syed suleman

Reputation: 542

Get your data in array like

$selected_items= explode( ";", "21;22;23" );

then use in_array( $option_value, $selected_items ); to detect if that option is selected.

Upvotes: 2

Swaraj Giri
Swaraj Giri

Reputation: 4037

Look into how you can- Normalize data

Till you do that, you can have a hack of splitting the string with ;

var data = "21;22;23"; var ids = data.split(';') will give you an array

of the ids ["21", "22", "23"]

Iterate over the ids and create your dropdown elements.

var html = '';
$.each(ids, function(id) {
   html += '<option value="' + id + "'>' + id + '</option>';
});

$('.some-dropdown').html(html);

Upvotes: 0

Related Questions