I have data in a select tag that is POSTed back to my script. I have the key in the POST array but need the corresponding value. How do I get this without querying the database for it?
<option value="1">My Value</option>
I have data in a select tag that is POSTed back to my script. I have the key in the POST array but need the corresponding value. How do I get this without querying the database for it?
<option value="1">My Value</option>
Don't you have it on the server side already? In the database or whatever storage? Sure you do.
So, get it from there.
When you post the form, the receiving program will receive the contents of the value
attribute for each field. Therefore, in the example you quoted, you will receive 1
.
If you actually want to receive My Value
(or at least have it readily to hand), then there's a number of options open to you:
Include it in the value
attribute, so it gets posted. eg <option value='1:My Value'>
. Then you can split the numeric value from the text value in the receiving program. This would work quite well, though the down side of this is that you're now adding extra overhead to the form post (admittedly not a huge amount, though).
Store the options array in the session. Then the whole array is accessible at any time without re-loading from the DB. The down side of this is that you'll end up cluttering up your session with loads of arbitrary data that doesn't need to be there.
Just get it from the DB and stop worrying; if you're using a decent DB, it'll have cached the value anyway from your previous page load when you populated the drop-box, so it isn't exactly a big overhead. Realistically, unless you've got a really big performance issue, I'd suggest this is the way to go.
I would suggest you go about this in a reverse manner. That is create the list in the back end and call it to its HTML counterpart. That way you would have both the values and its corresponding key.
Alternatively, you could, if your list is rather small (otherwise it will get a bit messy) simply check what the value is and assign its corresponding key in your logic, manually.
I noticed you mentioned that you already have both the values. Whats stopping you from matching the key with its value?
One way to do this, first one an array, 2nd an object:
<select name="">
<option value="[0,1,2,3]">Option one</option>
<option value="{foo:'bar',one:'two'}">Option two</option>
</select>
You can't - an alternative, if you wan't to avoid contacting the database, would be something like:
<option value="1|My Value">My Value</option>
And in your recieving script:
$values = explode("|", $_POST["yourselect"]);
var_dump($values);