0

I've got a html drop down <select> tag that I want to populate using the values from a POST. The variable name in question begins 'P' and is incremented by 1 each time, P1, P2, P3 etc etc.

How can I populate my drop down with this post data? I assume I need either a for or a for each loop in php?

Thanks

ianace
  • 1,646
  • 2
  • 17
  • 31
ajguk
  • 171
  • 1
  • 6
  • 16
  • What is the POST form you're getting data from? is it the same form? – Your Common Sense Apr 13 '11 at 13:50
  • what's the relationship between the posted data and P1...Pn? Do you mean that the page would accept the post and then form the select during page generation? or are you looking for an AJAX type solution? – Robot Woods Apr 13 '11 at 13:50
  • POST form is a separate form. Pn would sum it up yes. I'm thinking populating an array first from Pn then outputting this array to the html to create the values in the drop down? – ajguk Apr 13 '11 at 13:56
  • so, is the posted data the fully array (as with Steve's solution below) or is it just an integer telling you how many options need to be created? – Robot Woods Apr 13 '11 at 14:01

2 Answers2

0

I would suggest naming your variable P[0], P[1], P[2], etc. on the form generating your list of variables. If you do, then in the form processing page you can do:

if(is_array($_POST['P']))
{
    $arr = $_POST['P'];
    foreach($arr as $key => $val)
    {
        $buffer += '<option value="' . $key . '">' . $val . '</option>';
    }
}
$select = '<select name="somename">' . $buffer . '</select>';

So if it looks like an array to PHP, you will get an array.

Steve Mallory
  • 4,245
  • 1
  • 28
  • 31
  • Thanks, I took the $select line out though as I couldn't get it to wrok with it in, but here's what I have and it works well, thank you... `` – ajguk Apr 13 '11 at 14:30
0

Steve's answer is correct code-wise BUT...

Please don't put the contents of $_POST/$_GET directly in your output. It opens you up to a whole bunch of security problems. For example, in your POST data someone has inserted some HTML or JavaScript. In fact, in the example above, they could even inject malicious PHP.

Go and read up on how to sanitize user data for output. The method depends on the output destination. A simple way to sanitize HTML output is using htmlspecialchars(). There are also a number of good answers on this site. (e.g. Sanitizing user's data in GET by PHP )

Community
  • 1
  • 1
lxt
  • 1
  • Hi Yes thanks that is something I'll get to. I'm new to php but when I use vb etc I do sanitise my inputs. Thanks for the reminder though! – ajguk Apr 13 '11 at 14:46