[英]How to pass a PHP variable using the URL
我想使用 URL 传递一些 PHP 变量。
我尝试了以下代码:
链接.php
<html>
<body>
<?php
$a='Link1';
$b='Link2';
echo '<a href="pass.php?link=$a">Link 1</a>';
echo '<br/>';
echo '<a href="pass.php?link=$b">Link 2</a>';
?></body></html>`</pre></code>
pass.php
<pre><code>`<html>
<body>
<?php
if ($_GET['link']==$a)
{
echo "Link 1 Clicked";
} else {
echo "Link 2 Clicked";
}
?></body></html>
单击链接Link1
和Link2
,我得到“单击链接 2”。 为什么?
在您的 link.php 中,您的echo
语句必须是这样的:
echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
然后在你的 pass.php 中你不能使用$a
因为它没有用你想要的字符串值初始化。
您可以直接将其与这样的字符串进行比较:
if($_GET['link'] == 'Link1')
另一种方法是首先将变量初始化为您对 link.php 所做的相同的事情。 而且,更好的方法是将$a
和$b
变量包含在单个 PHP 文件中,然后将其包含在您将使用这些变量的所有页面中,正如 Tim Cooper 在他的帖子中提到的那样。 您也可以将其包含在会话中。
您分别在 A 和 B 的 href 中传递link=$a
和link=$b
。 它们被视为字符串,而不是变量。 以下应该为您解决这个问题:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
$a
的值也不包含在pass.php
。 我建议制作一个通用变量文件并将其包含在所有必要的页面上。
以上所有答案都是正确的,但我注意到一些非常重要的事情。 在变量和等号之间留一个空格可能会导致问题。 例如, (?variablename =value)
我在 Skytopia 的“ PHP、表单和 JavaScript 代码的超级有用部分”中找到了这个解决方案。
在“page1.php”或“page1.html”中:
// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a>
//or as I needed it.
<a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>
在“page2c.php”里面:
<?php
// Retrieve the URL variables (using PHP).
$num = $_GET['myNumber'];
$fruit = $_GET['myFruit'];
echo "Number: ".$num." Fruit: ".$fruit;
?>
使用这个简单的方法
$a='Link1';
$b='Link2';
echo "<a href=\"pass.php?link=$a\">Link 1</a>";
echo '<br/>';
echo "<a href=\"pass.php?link=$b\">Link 2</a>";
就放
$a='Link1';
$b='Link2';
在你的 pass.php 中,你会得到你的答案并在你的 link.php 中做一个双引号:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.