Search code examples
phpformsurlselecturlvariables

Append form value to URL that already has variables in it


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


Solution

  • 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>