简体   繁体   English

如何在PHP中将多个参数传递给URL

[英]How I can pass multiple parameters to URL in php

I have a problem in passing 2 parameters via URL I don't know how, so I wrote this: 我不知道如何通过URL传递2个参数时遇到问题,所以我这样写:

<form method="get" >
   <b>Enter the Quantity you want:</b>
   <input type="text" name="quantity">
</form>

<br><br>

<a href='./shopping-cart.php?part_id="<?php echo $_GET['part_id']; ?>"&quantity="<?php echo $_GET['quantity']; ?>"'>
   <img src="add_to_shopping_cart.png">
</a>

$_GET['part_id'] this var from another URL and I want to pass it again and $_GET['quantity'] quantity from form. $_GET['part_id']此变量来自另一个URL,我想再次传递它,并从表单中传递$_GET['quantity']数量。

You must use urlencode function for your parameters, and don't use the double quotes: 您必须对参数使用urlencode函数,并且不要使用双引号:

<a href='./shopping-cart.php?part_id=<?php echo urlencode($_GET['part_id']); ?>&quantity=<?php echo urlencode($_GET['quantity']); ?>'>

Even though, I suggest you to avoid long urls and use POST with hidden fields. 即使如此,我还是建议您避免使用长网址,并在隐藏字段中使用POST。

There's a few errors that I can see. 我可以看到一些错误。

You can't use $_GET['quantity'] if the user is entering it in without reloading the page (Remember, PHP is not client-side). 如果用户在不重新加载页面的情况下输入$_GET['quantity']则不能使用它(请记住,PHP不是客户端)。 Thus, I suggest using JavaScript for that. 因此,我建议为此使用JavaScript。

Javascript: 使用Javascript:

function buildUrl(a) {
   var qty = document.getElementById("qty").value; 
   a.href = "./shopping-cart.php?part_id="+<?php echo $_GET['part_id']; ?>
   +"&quantity="+qty;
}

As you no longer need to get a PHP variable from the current page, the form is obsolete and a simple link will do. 由于您不再需要从当前页面获取PHP变量,因此该表格已过时,并且可以通过简单的链接进行操作。

HTML: HTML:

<b>Enter the Quantity you want:</b>
<input type="text" name="quantity">
<a href='#' onclick="buildUrl(this);"> //onclick attribute triggers the JavaScript
    <img src="add_to_shopping_cart.png">
</a> 

You get this notice Undefined index: quantity cause you are trying to access an undefined variable. 您会收到以下通知: 未定义索引:数量,原因是您尝试访问未定义的变量。 If your page url is something like page_name.php?quantity=5 then $_GET['quantity] is set, otherwise it isn't. 如果您的页面网址类似于page_name.php?quantity=5则设置$_GET['quantity] ,否则不设置。

You should check if the $_GET variable exist. 您应该检查$_GET变量是否存在。 If so, use @user4035 answer to print the url. 如果是这样,请使用@ user4035答案打印URL。

if(isset($_GET['quantity']))
{ 
    //html code,the url
    //echo $_GET['quantity']
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM