I want to pass some PHP variables using the URL.
I tried the following code:
link.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>
Upon clicking the links Link1
and Link2
, I get "Link 2 clicked". Why?
To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.
Use PODS Style MySQL to Send ID in URL This is the most common method used in PHP to make URLs dynamic and send ID(s). Once we have created dynamic, hyper references, we are all set to use $_GET['id']; and store it in a variable. That way, we can use any logic on this selected ID.
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL.
In your link.php your echo
statement must be like this:
echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Then in your pass.php you cannot use $a
because it was not initialized with your intended string value.
You can directly compare it to a string like this:
if($_GET['link'] == 'Link1')
Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a
and $b
variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With