开发者

PHP form processing - how to capture text from field that has variable Name/ID

I have a form that has a field pulled from the database as a dropdown. I need to get the text selected in the dropdown but I don't know in advance what the field ID will be.

This is basically just a form that has already been generated. I don't need to pull anything from the database, it's already开发者_开发知识库 on this page. All I need to do is get the form information and email it, no writing to the database.

I know how to do the _Request for the other fields based on the ID but I'm not sure how to do this one. The ID changes. It can be ID=1, ID-2, etc.

I need to do something like: _REQUEST form element where ID is LIKE "ID[*]" or something similar.

Any suggestions or links to tutorials?

Here are a couple samples of what the dropdown renders on the page:

<div class="wrapperAttribsOptions">
<h4 class="optionName back"><label class="attribsSelect" for="attrib-  1">Model</label></h4>
<div class="back">
<select name="id[1]" id="attrib-1">
    <option value="45">VC3-4C</option>
    <option value="1">VC3-4PG</option>
    <option value="3">VC3-4SG</option>

<div class="wrapperAttribsOptions">
<h4 class="optionName back"><label class="attribsSelect" for="attrib-14">SPK   Model</label></h4>

<div class="back">
<select name="id[14]" id="attrib-14">
    <option value="43">SPK-4</option>
    <option value="44">SPK-8</option>
</select>

TIA


The brackets [] mean that PHP will create an array variable with the posted values. So you should have $_REQUEST['id'] as an array. There should be a value keyed by the number in the form ($_REQUEST['id'][1] in your first example, $_REQUEST['id'][14] in your second).

If there will just be one value (you don't say what you're trying to do with these values) then you can just shift it off the array.

$value = array_shift($_REQUEST['id']);

If there will be multiple values, you can loop through them:

foreach($_REQUEST['id'] as $number => $value) { ... }


EDIT: Scott Saunders is right, PHP will automatically create an array for you. If for some reason his code doesn't work, the below might still apply (could differ based on PHP configuration).

The easiest way would be using a regular expression:

foreach($_REQUEST as $key => $value)
{
    if(preg_match("/id\[[0-9]*\]/", $key))
    {
        // $key now contains the name, and $value the value.
    }
}

This is assuming the id will always be numerical.


If there is a large number of fields or the id values cannot be known, I would follow Arda's answer.

The alternative is to interrogate the id collection directly:

$id_1 = $_POST['id'][1];
$id_14 = $_POST['id'][14];

All items posted to the server with square brackets in their name are converted to an array. Having already specified the index, as you have done, may be more beneficial depending upon ones needs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜