Search code examples
phpgetsubstrstrpos

Refresh page and change 1 $_GET variable


I've been wondering this for a while since I started PHP. Some sites use filtering options. Sometimes some of those filters are completely random. For example someone might be viewing: products.php?c=1&p=1&s=100 In that example, let's assume c is the category, p is the page and s is the start price.

If the viewing user were to change the start price or flip to the next page using a hyperlink, how would one change only a single $_GET[] variable while leaving the others untouched. I do have a small script in PHP to obtain the current URI however, I just can't figure out how I'd change only that variable while keeping the others untouched and refresh the page? I've looked at substr(), strpos(), and ereg_replace() and I just can't figure it out!

I am really sorry if this is a dumb question, I feel like I've missed something really easy that can fix this but I'm genuinely stuck guys.

Thanks so much in advance! Mike.


Solution

  • It depends on whether or not you're in a form or a URL.

    If you're in a form it's easy because the user changes the input field they want changed and the others stay there:

    <form>
        <input type="p" value="1" />
        <input type="c" value="1" />
        <input type="s" value="100" />
        <input type="submit" />
    </form>
    

    The problem with the URL based method is you would have to set the url for each one like this:

    <a href="?p=1&c=1&s=1">$1 Starting Price</a>
    <a href="?p=1&c=1&s=10">$10 Starting Price</a>
    <a href="?p=1&c=1&s=100">$100 Starting Price</a>
    

    You'd have to do this to make it dynamic:

    <a href="?p=<?php echo urlencode($_GET['p']) ?>&c=<?php echo urlencode($_GET['c']) ?>&s=1">$1 Starting Price</a>
    

    That's a lot of typing for all of your links. You could make a PHP function to handle changing the one value like this:

    function genUrl($newKey, $newVal) {
        $url = '?';
        foreach ($_GET as $key => $val) {
            if ($url != '?') {
                $url .= '&';
            }
    
            $url .= urlencode($key) . '=' ($key == $newKey ? $newVal : urlencode($val));
        }
    
        return $url;
    }
    

    And your html would look like this:

    <a href="<?php echo genUrl('s', 1) ?>">$1 Starting Price</a>
    <a href="<?php echo genUrl('s', 10) ?>">$1 Starting Price</a>
    <a href="<?php echo genUrl('s', 100) ?>">$1 Starting Price</a>