0

I want to pass more than one variable in the URL bar using PHP, however I want one of the variables to be added onto another existing variable in the URL bar.

For example:
Let's say you have: test.php?u=2 and let's suppose one of the fields is age. Once I click submit I want the URL to look like test.php?u=2&age=22 but on the same page.

How could I do this? Would I have to redirect the user again?

master
  • 1
  • 1
  • 2
  • Is your question about how to construct the URL? – Pekka May 07 '11 at 21:49
  • No. My question is how do I add another variable to the same URL. – master May 07 '11 at 21:52
  • With or without reloading the page? The latter is not possible – Pekka May 07 '11 at 21:54
  • With reloading the same page. – master May 07 '11 at 21:56
  • 1
    @master from PHP, a header redirect is your only choice then. However, building the URL is more tricky than adding `&age=22` to the query string if you want to do it properly. – Pekka May 07 '11 at 21:57
  • Alright. Thanks for the instant help. I'll try to see what I can do and if it doesn't work I'll reply back. EDIT: I already built the URL, it's just that I want another variable on the same page instead of redirecting the user. – master May 07 '11 at 21:58
  • See this question for the safest way to build the new query string: [Strip off URL parameter with PHP](http://stackoverflow.com/q/4937478) It's about the exact opposite of what you want, but the approach is the same – Pekka May 07 '11 at 22:01

2 Answers2

1

<form method="get" action="?"> - use this as your form tag. It'll submit to the same page, with all the form values in the querystring, accessible via $_GET.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
David Fells
  • 6,678
  • 1
  • 22
  • 34
0

You can write code that injects all request variables into the form that the button submits. For example:

<form ... >
    <?php foreach($_REQUEST as $key => $value) {
              echo sprintf('<input type="hidden" name="%s" value="%s" />', 
                  htmlspecialchars($key),
                  htmlspecialchars($value));
          }
    ?>
<!-- the one you want to add follows -->
<input type="hidden" name="age" value="22" />
<input type="submit" />
</form>

It isn't pretty, but it works (if you don't mind that the vars from either $_GET or $_POST will actually end up being submitted with other method, whichever one it is the form uses).

Jon
  • 428,835
  • 81
  • 738
  • 806