0

So I have a page with 2 different PHP code example;

<?php

blablabla...

?>


<?php

testtestest...

?>

and I have 1 form with 2 submit buttons but I dont know how I can link 1 button to execute php code 1 and the other button to execute php code 2.

Now the 2 buttons only execute php code 1 which is not what i want.

jonny
  • 3
  • 2
  • Very detailed code example! Have you tried using [if](https://www.php.net/manual/en/control-structures.if.php)? – brombeer Mar 06 '20 at 10:05
  • Yes, I have tried if and if then else but it also didnt work – jonny Mar 06 '20 at 10:06
  • 1
    `if (isset($_POST['NameOfTheSubmit1'])) { your first code } else if (isset($_POST['NameOfTheSubmit2'])) { your second code }` could do the trick – Cid Mar 06 '20 at 10:08
  • @Cid I also tried that code but suprisingly it doesnt work – jonny Mar 06 '20 at 10:17
  • 3
    Maybe you could post your code so people don't have to guess button names or if you're using GET or POST or if your form is set up correct. – brombeer Mar 06 '20 at 10:19
  • 3
    Does this answer your question? [Two submit buttons in one form](https://stackoverflow.com/questions/547821/two-submit-buttons-in-one-form) – Cid Mar 06 '20 at 10:21

2 Answers2

2

Give a name to your buttons, and check the name which is submitted :

<?php if (isset($_POST['submit_1'])) { ... } else if (isset($_POST['submit_2'])) { ... } ?>
<form action="" method="post">
  <input type="submit" name="submit_1">
  <input type="submit" name="submit_2">
</form>
Altherius
  • 754
  • 7
  • 23
0

First answer: create two seperate forms

<form action="page1.php">
<input type=button name=button1>
</form>


<form action="page2.php">
<input type=button name=button2>
</form>

Answer after OP commented: use a "hidden" field in HTML which will contain the button which is pressed (keep it simple and use a single number like 1 is button 1 and 2 is the other button)

You put a javscript function on both buttons that will change the value of this field when being pressed.

In your PHP Script page where you land if you press the button you just do

if ($_POST[hiddenfield]>1)
{//button1 is pressed

}else
{//button2 is pressed

}

if you need help with the hidden field or javascript, comment and I'll show you the code

  • I can't. I have 1 form with info inside such as, name, lastname, email etc – jonny Mar 06 '20 at 10:08
  • then I would suggest an invisible field that tracks which buttons is pressed but I'll edit my answer, give me a min – Leerjongen PHP Mar 06 '20 at 10:10
  • 2
    oh yea look at @Cid 's comment on your question, its basically the same but with less code and faster! So its better then mine – Leerjongen PHP Mar 06 '20 at 10:13
  • I tend not to use $_POST["buttonname"] because it won't fire when there's a submit for any other reason. Like user refreshes the page -> post[button] will be empty so no code will be executed. But this is very dependable on how your solution looks like.. – Leerjongen PHP Mar 06 '20 at 10:32