开发者

Populate html drop down from POST data in php form

开发者 https://www.devze.com 2023-02-25 10:51 出处:网络
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.

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 m开发者_StackOverflowy drop down with this post data? I assume I need either a for or a for each loop in php?

Thanks


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'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 )

0

精彩评论

暂无评论...
验证码 换一张
取 消