How to know which button was clicked

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
shoaibmohammeda
Forum Newbie
Posts: 2
Joined: Fri Feb 13, 2009 12:14 pm

How to know which button was clicked

Post by shoaibmohammeda »

Hello,

As every one says, Im pretty new to PHP. I was going through a tutorial & suddenly got stucked up in a problem.

Supposingly in a form i have two buttons "Login","Sign Up" in a SAME PAGE

How do i know which button was clicked?

Hoping of getting guidance from you guys

Thank You
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: How to know which button was clicked

Post by sparrrow »

The submit buttons have name and value attributes that work the same as the ones for other form inputs. Assign a unique name and/or value to each button, and whichever one is clicked will have it's value assigned to the corresponding name key in the post data.

Form

Code: Select all

<input type="submit" name="submit" value="Sign Up" />
target POST page

Code: Select all

echo $_POST['submit']; //Returns "Sign Up"
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: How to know which button was clicked

Post by pickle »

Only the submit button that was clicked will appear in $_POST.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
bugrush
Forum Newbie
Posts: 15
Joined: Tue Dec 16, 2008 3:00 pm

Re: How to know which button was clicked

Post by bugrush »

You can check which button was clicked like this:

Code: Select all

if(isset($_POST['sign_up'])) {
    //signup
} elseif(isset($_POST['login'])) {
    //login
}
And about form buttons: I prefer using <button type="submit">Button Caption</button> over <input type="submit" value="Button Caption" /> because I like to keep button captions and values separate. If you use input for button then you can't really use it's value in php.
This feels cleaner:

Code: Select all

<button type="submit" name="action" value="sign_up">Sign Up</button>
<button type="submit" name="action" value="login">Login</button>
shoaibmohammeda
Forum Newbie
Posts: 2
Joined: Fri Feb 13, 2009 12:14 pm

Re: How to know which button was clicked

Post by shoaibmohammeda »

Thank you guyz..

I dint expect such a help..

Really thank you.
Post Reply