Solved

Making links / modifying query string in PHP

Posted on 2009-03-29
9
323 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
 
LVL 12

Expert Comment

by:alien109
ID: 24014314
oops.

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

should be

params.push(i + "=" gridState[i]);
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

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 108

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

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
This article discusses four methods for overlaying images in a container on a web page
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…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 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

21 Experts available now in Live!

Get 1:1 Help Now