dslfq06464
dslfq06464
采纳率0%
2018-05-25 11:53 阅读 101
已采纳

PHP表单数据检查提交按钮名称

I have two forms on the same page, each with different fields and different submit button names.

<button type="submit" name="formOne">Submit form</button>
<button type="submit" name="formTwo">Submit form</button>

On my mailer.php page I would like to check which submit button has been clicked, and process the code accordingly.

The code I have so far works for a single form, as follows;

if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
    // my form 1 data
    // do stuff
}

However I thought I coulld add an if/else to check which submit button was clicked, something like;

if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
    if($_POST['formOne']){
        // form 1 data
        // my form 1 data
        // do stuff
    }
    if($_POST['formTwo']){
        // form 2 data
        // my form 2 data
        // do stuff
    }
}

This doesn't seem to work. The error I receive is;

Notice: Undefined index: formOnein ... line 7

How can I achieve this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douzhang6646 douzhang6646 2018-05-25 12:07

    If you want, you can alternatively use hidden inputs. You can access hidden inputs from php just like a normal text input.

    <form method="GET" action="https://postman-echo.com/get">
        <input type="hidden" name="form" value="one" />
        <button type="submit">Submit form</button>
    </form>

    </div>
    
    点赞 评论 复制链接分享
  • drllqg2903 drllqg2903 2018-05-25 11:55

    You just forgot to check if the var isset().

    if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
        if(isset($_POST['formOne'])){
            // form 1 data
            // my form 1 data
            // do stuff
        }
        if(isset($_POST['formTwo'])){
            // form 2 data
            // my form 2 data
            // do stuff
        }
    }
    
    点赞 评论 复制链接分享
  • dpvp56187 dpvp56187 2018-05-25 12:30

    Instead of using

    <button type="submit" name="formOne">Submit form</button> <button type="submit" name="formTwo">Submit form</button>

    use

    <input type="submit" name="formOne" value="Submit Form"/>
    <input type="submit" name="formTwo" value="Submit Form"/>
    

    php code:-

     <? if(isset($_POST['formOne'])){echo "form One";} elseif(isset($_POST['formTwo'])){echo "form Two"; }?>
    
    点赞 评论 复制链接分享

相关推荐