Multiple forms and one PHP receiver

2019-08-14 15:13发布

问题:

I have MySQL generating forms on one page with the same action and submit button. The number of forms vary. They all call the same PHP file when submitted. Also, I have one PHP file which collects the data upon submission. See the example below.

The problem is when one of the forms is submitted, values get confused with different fields from different forms. Example: When form1 is submitted, PHP receives the form6's values.

How can I make sure each form submits its own values?

HTML Code Example:

<form method="POST" action="index.php?action=newhistory" name="history_1">
    <input type="hidden" name="id" value="1">
    <input type="text" name="history">
    <input type="submit" name="add_history" value="Submit">
</form>

<form method="POST" action="index.php?action=newhistory" name="history_6">
    <input type="hidden" name="id" value="6">
    <input type="text" name="history">
    <input type="submit" name="add_history" value="Submit">
</form>

PHP Code Example:

case 'newhistory':

    $id = $_POST['id'];
    $history = $_POST['history'];

    $sql = mysql_query("INSERT INTO history (id, history) VALUES('".$id."', '".$history."')", $link);

    break;

Any solutions?

回答1:

It will submit the content encapsulated by the <form></form> tags. Having several form's action attribute point to the same page should not create the problem you describe.

The code you wrote here looks fine. Check your HTML code, and ensure you have the corrent <form></form> tags surrounding the elements of each form.



回答2:

Please use different names for the submit button, then check.

if(isset($_POST('add_history'))
{
}

if(isset($_POST('add_history1'))
{
}


回答3:

If you hit submit in one form, the browser is supposed to send only the values from this form. When form1 is submitted, PHP will NOT receive the form6's values. Maybe you didn't close the form tag properly or have any JavaScript going wild.