Making links / modifying query string in PHP

I'm building a page in PHP that shows a grid with some records. It uses sorting/filtering/pagination. This means there's a few links on the page that "do" things to the page by modifying some of the $_GET parameters. Examples:

<a href="?sort=asc">Sort Ascending</a>
<a href="?sort=desc">Sort Descending</a>
<a href="?filter=a">Filter by letter A</a>
<a href="?filter=z">Filter by letter Z</a>
<a href="?page=3">Go to page 3</a>
<a href="?page=1">Go to page 1</a>

The problem is that there may have already been some $_GET parameters specified in the query string, example:

http://www.mywebsite.com/mypage.php?foo=bar&page=2&query=hello&sort=ASC

These links currently wipe out everything that was in the query string. Really I want to "tack on" the given parameters to the query string, or "modify" them if they were already specified, and preserve all the other parameters that may have been there before.

Here's an example using the links and the url I gave you above:

<a href="?foo=bar&page=2&query=hello&sort=ASC">Sort Ascending</a>
<a href="?foo=bar&page=2&query=hello&sort=DESC">Sort Descending</a>
<a href="?foo=bar&page=2&query=hello&sort=ASC&filter=a">Filter by letter A</a>
<a href="?foo=bar&page=2&query=hello&sort=ASC&filter=b">Filter by letter Z</a>
<a href="?foo=bar&page=3&query=hello&sort=ASC">Go to page 3</a>
<a href="?foo=bar&page=1&query=hello&sort=ASC">Go to page 1</a>

I figure I'll need some kind of PHP function to read the existing parameters and assemble a new query string by merging the old parameters and the new new parameters, but how do I go about doing that in PHP?
LVL 31
Frosty555Asked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
If you are using PHP 5, you can use the builtin function http_build_query() to create the query. The add2URL() function below takes the parameters from the current URL using $_GET, and adds the parameters you provide in the input. You can overwrite existing parameters.
function add2URL($data) {
  $a = array_merge($_GET,$data);
  return http_build_query($a);
}
 
echo '<a href="?'.add2URL(array('sort'=>'name')).'">Sort by name</a>';
echo '<a href="?'.add2URL(array('sort'=>'age')).'">Sort by age</a>';

Open in new window

0
 
nanharbisonCommented:
You need to get the query string from the page you are already on and append your sort criteria to the end of it.
$_SERVER[QUERY_STRING]
0
 
nanharbisonCommented:
you can find out the name of this server variable by putting this on your page:

 echo "<pre>";
 print_r($_SERVER);
  echo '</pre>';
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
alien109Commented:
I would read in the parameters from the querystring, and set them in javascript variables. then use javascript on the clientside to assemble the appropriate params... like

<script type="tex/javascript">

var gridState = {
      page:<?=$_GET['page']?>
      filter:"<?=$_GET['filter']?>",
      sort:"<?=$_GET['sort']?>"
}

function getParamsString()
{
      var params = [];
      for(var i in gridState)
      {
            paramsArray.push(i + "=" gridState[i]);
      }
      return params.join("&");
}

function goToPage(num)
{
      gridState.page = num;
      var url = "somepage.html?" + getParamsString();
      console.log(url);
}
<script>

<a href="#" onclick="goToPage(3);return false;">Go to page 3</a>

I haven't actually tested that code, just spit that out. But - should get you started in the right direction.
0
 
alien109Commented:
oops.

paramsArray.push(i + "=" gridState[i]);

should be

params.push(i + "=" gridState[i]);
0
 
Ray PaseurCommented:

<?php // RAY_add_to_GET_query_string.php
error_reporting(E_ALL);
echo "<pre>";
 
// SHOW WHAT IS IN PHP SELF
echo "PHP_SELF "; var_dump($_SERVER["PHP_SELF"]);
 
// SHOW WHAT IS IN THE REQUEST URI
echo "REQUEST_URI "; var_dump($_SERVER["REQUEST_URI"]);
 
 
 
 
 
// SAMPLE OF SOMETHING TO ADD TO THE QUERY STRING (COULD BE ANYTHING)
$new = 'foo=bar';
 
 
 
 
// CONSTRUCT A NEW GET STRING
$get = '?';
if (!empty($_GET))
{
   foreach ($_GET as $key => $val)
   {
      $get .= $key . '=' . urlencode(stripslashes($val)) . '&';
   }
}
 
// ADD THE NEW VAR TO THE URL
$get .= $new;
 
// MAKE THE NEW URL
$url = $_SERVER["PHP_SELF"] . "$get";
 
// SHOW THE RESULTS
echo "NEW URL "; var_dump($url);

Open in new window

0
 
Frosty555Author Commented:
cxr - that was incredibly sleek, and the only solution here that correctly handled the case where I specify parameters that already exists in the query string. No wonder you're a Sage in this zone.

I am running PHP4, not 5, so http_build_query() did not work, however there is a php4 implementation of it provided on php's website. I've attached it to the code snippet.
<?php
if(!function_exists('http_build_query')) {
    function http_build_query($data,$prefix=null,$sep='',$key='') {
        $ret    = array();
            foreach((array)$data as $k => $v) {
                $k    = urlencode($k);
                if(is_int($k) && $prefix != null) {
                    $k    = $prefix.$k;
                };
                if(!empty($key)) {
                    $k    = $key."[".$k."]";
                };
 
                if(is_array($v) || is_object($v)) {
                    array_push($ret,http_build_query($v,"",$sep,$k));
                }
                else {
                    array_push($ret,$k."=".urlencode($v));
                };
            };
 
        if(empty($sep)) {
            $sep = ini_get("arg_separator.output");
        };
 
        return    implode($sep, $ret);
    };
};
?>

Open in new window

0
 
Ray PaseurCommented:
@Frosty555: Amazing!  

Did you even test the solution I posted?  Unless I am missing something, it was the first correct and complete solution.  It works just fine for PHP4 and PHP5.  Moreover, it teaches the way to achieve what you asked for, via its comments and its output.  

Instead it appears that you took a solution that did not work for you because of PHP4, researched until you found an answer, and then awarded the points for the unworking solution.

In the future, you might want to consider awarding some of the points to the first correct response, eh?

Best regards, ~Ray
0
 
Roger BaklundCommented:
Ray, if you re-read the question, you will see that he asked for a way to "assemble a new query string by merging the old parameters and the new new parameters". Your code does not do that.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.