繁体   English   中英

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

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

我不知道如何通过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']此变量来自另一个URL,我想再次传递它,并从表单中传递$_GET['quantity']数量。

您必须对参数使用urlencode函数,并且不要使用双引号:

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

即使如此,我还是建议您避免使用长网址,并在隐藏字段中使用POST。

我可以看到一些错误。

如果用户在不重新加载页面的情况下输入$_GET['quantity']则不能使用它(请记住,PHP不是客户端)。 因此,我建议为此使用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;
}

由于您不再需要从当前页面获取PHP变量,因此该表格已过时,并且可以通过简单的链接进行操作。

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> 

您会收到以下通知: 未定义索引:数量,原因是您尝试访问未定义的变量。 如果您的页面网址类似于page_name.php?quantity=5则设置$_GET['quantity] ,否则不设置。

您应该检查$_GET变量是否存在。 如果是这样,请使用@ 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