Show data from database in multiple dropdowns using PHP

I am using Chosen.js to display dropdown menus with multiple choices in my forms. All of this user-selected data enters the mysql database on a single line, separated by a ";" So far so good.

Now my problem is that I want to provide my users with an edit form where they can edit all the data. So I have to read data from the database and show it on the form. But what is the correct way for a dropdown menu with multiple choices?

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

      

Data stored in the database such as:. "21; 22; 23"

I'm really stuck with this ...

+3


source to share


2 answers


Get your data in an array like

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



then use in_array( $option_value, $selected_items );

to determine if this option is selected.

+2


source


See how you can: Normalize data p>

Before that, you can hack the string with ;

var data = "21;22;23"; var ids = data.split(';')

will give you an array



identifiers ["21", "22", "23"]

Iterate over ids and create your dropdowns.

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

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

      

0


source







All Articles