Append form value to URL that already has variables in it

1.4k Views Asked by At

I've got a page showing the results of a MYSQL query written in PHP. The URL has the variables that the user submitted on the previous page as:

www.mydomain.com/search/?var1=xx&var2=xx&var3=xx

When the user is on the results page they need to be able to sort the results. To do this I've got a SELECT form

<form action="/search<?php echo $urlQuery; ?>"  name="order "class="formsrch" method="post" >
            <label>sort by:</label>
            <select class="order" id="order" name="order" onChange="this.form.submit()">
                <option value="pricedesc">Price High to Low</option>
                <option value="priceasc">Price Low to High</option>
                <option value="dist">Distance</option>
            </select>
        </form>

The variable $urlQuery contains the string to be appended onto the url: i.e. $urlQuery = "?var1=xx&var2=xx&var3=xx"

The problem is that when the form is submitted the page is reloaded and at the end of the url is ?order=dist.

Is there a way of replacing the question mark with an ampersand so the page will load and the value of order can be retreived?

Or, if anyone has a better way of doing the whole thing I'm definitely open to suggestions. Thanks

4

There are 4 best solutions below

0
On BEST ANSWER

why don't you put them in the form as hidden?

<?php
$extraVars = "";
  foreach($_GET AS $key=>$value) {
   $extraVars .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />';
  }
?>
<form action="/search"  name="order "class="formsrch" method="post" >
    <?php echo $extraVars;?>
    <label>sort by:</label>
    <select class="order" id="order" name="order" onChange="this.form.submit()">
        <option value="pricedesc">Price High to Low</option>
        <option value="priceasc">Price Low to High</option>
        <option value="dist">Distance</option>
    </select>
</form>
0
On

You could make a hidden field for each of the variables you want to transfer so that they get appended too.

Better still, make the method of the form get and then access all the variables with the $_REQUEST global in the backend script.

0
On

Output the other variables as <input type="hidden" name="var1" value="xx" /> instead of as the form action, so they'll get taken into your query string.

0
On

With this action="/search" and $urlQuery = "?var1=xx&var2=xx&var3=xx"

then to have the value appended on the querysting you should change the form method to "GET".

If you want to keep the form method to "POST" then some javascript would be required to change the action of the form when the form is submitted.