views:

41

answers:

3

I have some database information that is being shown on a page.

I am using a pagination class that uses the $_GET['page'] variable in the url. When you click on a different pagination anchor tag, it changes $_GET['page'] to a new number in the url and shows the corresponding results.

I have sort and search features which uses the $_GET['searchby'] and $_GET['search_input'] variables. The user enters their search criteria on a form that is using GET. The variables are then put into the url allowing for the correct results to be shown.

The problem I am having is that whenever I click on a pagination link, it adds the $_GET['page'] variable to end of the url and erases $_GET['searchby'] or $_GET['search_input']. When I submit the search form, it adds $_GET['searchby'] and $_GET['search_input'] but erases $_GET['page'].

How can I add GET variables to the end of the current page url using the anchor tag and search/sort form without having it erase any existing GET variables, but overriding them if they're the same GET variable name?

+1  A: 

Try this:

if (strpos($_SERVER['REQUEST_URI'], '?') !== false)
{
  $url = $_SERVER['REQUEST_URI'] . '&var=value';
}
else
{
  $url = $_SERVER['REQUEST_URI'] . '?var=value';
}

<a href="<php echo $url;>">Go</a>

Note that $_SERVER['REQUEST_URI'] gives you current url including query string value.

Sarfraz
Jamie Wong
I'll try it out. How can I solve that problem for the GET variables that are added to the url using a form?
zeckdude
@zeckdude: It shouldn't matter where the `GET` variables came from
jigfox
@phleet: I thought that initially but forgot to write the condition for that, thanks anyways.
Sarfraz
@phleet `
jigfox
@Jens Fahnenbruck: That's shorter and better.
Sarfraz
+1  A: 
$query_string = http_build_query(array_merge($_GET, array('page' => $page)));
Col. Shrapnel
what about the get variables that are being added by the form?
zeckdude
@zeckdude aren't they in the $_GET array already?
Col. Shrapnel
@Col. Shrapnel - No, they are only added by the get action using the form when the user searches on the form.
zeckdude
@zeckdude it seems you're missing something. WHEN user searches something, you HAVE the search criteria in the $_GET array. Your question was `How can I add GET variables`, so we assume we have these variables already. If you still don't understand it' you'd better explain. Or you'd better just try it. Cause my code answers your question exactly.
Col. Shrapnel