Solved

Making links / modifying query string in PHP

Posted on 2009-03-29
9
328 Views
Last Modified: 2013-12-13
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?
0
Comment
Question by:Frosty555
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +2
9 Comments
 
LVL 17

Expert Comment

by:nanharbison
ID: 24014249
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
 
LVL 17

Expert Comment

by:nanharbison
ID: 24014251
you can find out the name of this server variable by putting this on your page:

 echo "<pre>";
 print_r($_SERVER);
  echo '</pre>';
0
 
LVL 12

Expert Comment

by:alien109
ID: 24014311
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Expert Comment

by:alien109
ID: 24014314
oops.

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

should be

params.push(i + "=" gridState[i]);
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 24014440

<?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
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
ID: 24014549
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
 
LVL 31

Author Comment

by:Frosty555
ID: 24034755
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 24038457
@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
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24039829
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

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question