Repopulating a Multiple Select Box

Hi folks,

I’m having a bit of trouble with a small problem. Here is a simple rundown of what I’m trying to do.

I have three tables with a few rows like so:


person     |      state     |      person_state_lookup
-----------------------------------------------------------
id                id               person_id
name              state            state_id

When a person registers, they are able to select as many states as desired via a multiple select box. Saving the information to the database is pretty straightforward; my problem arises when trying to repopulate the multi-select box with their saved values.

How would I go about comparing state to person_state_lookup so that when there is a match, I can add a value of selected to the <option>?

I fear I’m over-complicating how to go about accomplishing this. Any insight or links would be greatly appreciated. Thanks!

You shouldnt name a table with the same name as a field, so rename your state table ‘state_t’

 
SELECT state
 FROM state_t
  JOIN person_state_lookup
   ON person_state_lookup.state_id = state_t.id
WHERE person_id = '20'

you can replace the 20 for a variable holding the persons ID your interested in

Hi Mandes, thank you for your reply.

My table names are unique (simplified for the example) but I will certainly keep that in mind. Your post helped me find a solution to my problem. What I ended up doing was this:


SELECT state_id, state_name FROM sales_states_lookup
INNER JOIN sales_states ON sales_states.id = sales_states_lookup.state_id
WHERE sales_id='$user_id'

This allowed me to compare the two arrays (all states against previously selected) like so:


		foreach($states as $state) {
			if (in_array($state, $previously_selected)) {
				$state_item .= "I am selected";
					} else {
				$state_item .= "I am not selected";	
			}
		}


I imagine there may be a more efficient way to achieve this but it appears to do the trick for now. Thanks again for your input; it’s appreciated.

Looks good enough to me