views:

224

answers:

5

I have some PHP code that generates dynamic tables of data on the fly. By clicking various links you "refine" the tables of data. What I'd like is each of these links to retain the current GET information and add to it. IE:

$allPreviousVars = ???; // Could be 20+ vars
echo "<a href='".$allPreviousVars."&newVar=2'>Link</a>";

I can think of ways to do it by iterating through $_GET with a loop, but surely there is a quicker way to do this?

A: 

Your best bet is, as you suggested, to loop over the contents of $_GET, constructing the URL from a mixture of the existing query parameters plus your overridden bits.

Rob
+8  A: 

How about $_SERVER["QUERY_STRING"]?

EDIT: Since you were kind enough to give me credit for this answer, I should add one thing. You should wrap the above variable in htmlspecialchars() before you output it. Otherwise someone could type a URL with "> in it, and it would break your link.

JW
I knew I saw something like that earlier. Perfect, thanks.
Andy Moore
+1  A: 

Use http_build_query() if you need to generate a query-string from a modified array. If you just want the querystring sent to the current page, do as suggested and use $_SERVER["QUERY_STRING"].

Emil H
A: 

I would probably do this:

$query = mySanitizeFunction($_GET);
$url = http_build_query($query) . '&newVar=2';
George Crawford
That'll break your URL if $_GET is empty, though.
pinkgothic
+1  A: 

I do this as follows:

<?php echo http_build_query(array_merge($_GET, array('foo'=>'bar', 'foo2'=>'bar2')); ?>

Note that any existing 'foo' or 'foo2' keys would be replaced.

Ciaran McNulty