Solved

Making links / modifying query string in PHP

Posted on 2009-03-29
9
325 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
  • 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 12

Expert Comment

by:alien109
ID: 24014314
oops.

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

should be

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

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 109

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
PHPStorm debugging issues 1 44
hasing a url 16 23
Loop through multiple arrays 13 27
Cookie not unsetting 7 18
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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.

815 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now