ds3422222 2013-06-30 15:11
浏览 24
已采纳

too long

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.

  • 写回答

2条回答 默认 最新

  • dqroktbn005028 2013-06-30 15:22
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大