检测哪个表单发送选择元素的值| PHP

Im working with php and html. My question is: How can I detect which form is sending its select element's value to action page.

<?php foreach($myarray as $arr){ ?>

<form name="uniqueform_<?=$arr["product_id]?>" method="post" action="action.php">
    <select name="letters">
        <option value='a'>a</option>
        <option value='b'>b</option>
        <option value='c'>c</option>
    </select>
    <input type="submit" value="Send"/>
</form>

<?php } ?>

action.php

<?php
$myselect_value = $_POST["letters"];

echo $myselect_value; //returns null;

?>

When I press Send button Im going to action page but select value is Null when use echo or var_dump();

I think php can't detect which form is posted to action page. How can I solve this issue? It is very annoying.

Fiddle: http://jsfiddle.net/8Rzb8/1/

You could do it with differently named submit buttons, or just use a hidden field:

<input type="hidden" name="form" value="uniqueform_<?=$arr["product_id]?>">

Then check $_POST['form'].

You need a field to identify the form in question. Example:

  • add to your form:
<input type="hidden" name="product_id" value="<?=$arr["product_id]?>" />
  • in your action.php, examine $_POST['product_id'] to determine which form was submitted.

For example, if the product id is 7, then $_POST['product_id'] is 7, and the form was uniqueform_7.

Hi the simple answer to this is name the submit buttons different names, for example

<input type="submit" value="Send"/>

you have no name there

 <form name="form1" >
   ....
    <input type="submit" value="Send" name="submit_frm1" />
  </form>

 <form name="form2" >
   ....
    <input type="submit" value="Send" name="submit_frm2" />
  </form>

Then you just check

if(isset($_POST['submit_frm1'] ){
   ... do some stuff for form1
}else if(isset($_POST['submit_frm2'] ){
   ... do some stuff for form2
}

I should note, however it's generally a bad practice to share form element names. So you really don't / shouldn't name those selects the same in the first place, It will make re-populating them, in the case of an error, a real pain.

Personally, I'd just name them differently, or put another way. Prefix all your form elements with an identifier. So

 <form name="frm1" >
   ....
    <select name="frm1_select" > ... </select>
    <input type="submit" value="Send" name="frm1_submit" />
  </form>

 <form name="frm2" >
   ....
    <select name="frm2_select" > ... </select>
    <input type="submit" value="Send" name="frm2_submit" />
  </form>

Then on the back end you can separate them with really simple code, preg_match(), explode(), substr() etc.. And generate them with equally simple code. I can give examples of this If you need me too.