Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

track selecting and unselecting an option When updating a table

Tags:

html

php

mysql

I have three tables (I simplified it in this question) :

Table 1

id | Name
-----------
1  | John
2  | Smith


Table 2

id | Title
-----------
1  | Developer
2  | Web Developer
3  | A New Title

Table 3 (links between 1 and 2)

idName | idTitle
-----------
1      | 1
1      | 2
2      | 1

My problem is with the update page. My HTML is <select multiple> ... options ... </select> and I am using chosen to select and deselect options. I am trying to do this with PHP only. Lets say that we have the following scenario: The administrator wanted to remove the 'Developer' Title for 'John' and add 'New Title' for 'John'. He/She will deselect Title id 1 and select id 3. When He/She submits the form I will get two select values: id 1 (the one that he selected) and id 2 (the one that was already there). But I will not get id 3 because he deselected it.

What I am struggling with is : when the user posted the new selected values the ones that were deselected were not submitted with the form. There is no way for me to track the ones that were deselected so I can delete them from my table. How do you update your table with the new changes then? Do you delete what is already existed in that table and add the ids again? Is there a better option?

UPDATE : It seems @wander answer is less destructive than the other ones. However, @wonder did not explain how to compute step 4 in his answer. to distinguesh between new selected options, already existing selected options, and deselected options.

like image 458
syrkull Avatar asked Dec 03 '22 18:12

syrkull


2 Answers

There's no need to submit the deselected one. e.g.

  1. John has two titles(Developer and Web Developer) saved in database.
  2. The administrator opens the page, selects 'New Title', deselects 'Developer' and clicks submit.
  3. Now on server side, we can get
    • the title list of John stored in database: Developer and Web Developer
    • title list submitted from the users: Web Developer and New Title
  4. We compare the two title lists and figure out: we shall delete Developer title and add New Title on John.
like image 156
wander Avatar answered Dec 06 '22 09:12

wander


You could add hidden fields before the select menu which will cause 0/falsey values to also be sent to PHP.

<input type="hidden" name="stuff[]" value="0" />
<input type="hidden" name="stuff[]" value="0" />
<input type="hidden" name="stuff[]" value="0" />
<select multiple name="stuff[]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

This is similar to how you would send unchecked check boxes to the server:

https://stackoverflow.com/a/1992745/268074 (note the answer without JS)

like image 43
Petah Avatar answered Dec 06 '22 09:12

Petah