Page 1 of 1

Problem in passing variables through link

Posted: Fri Jul 23, 2010 12:45 pm
by K-Z
Hi...I am facing problem in passing php variables through link. I want to pass variable $x to a.php file and I am using the syntax:

Code: Select all

<?php echo "<a href="a.php?var=$x">link</a></p>"; ?>
Please help me...whts wrong in the statement..??

Re: Problem in passing variables through link

Posted: Fri Jul 23, 2010 12:56 pm
by Jade
One thing to remember is that a hyperlink can't have spaces or characters in the name otherwise it breaks the href value. You can fix that by putting quotes around the whole href value and by using htmlentities.

Code: Select all

<?php echo "<a href=\"a.php?var=" . htmlentities($x) . "\">link</a></p>"; ?>
If you try to access $x on the a.php page you won't find it because it doesn't exists. However you can get the value that was in x that you passed to the page by doing this:

Code: Select all

<?php
$x = $_GET['var'];

echo $x;
?>
Big picture, if you need a variable to span several pages then you should be using a session like this:

b.php file

Code: Select all

<?php
session_start(); 
$_SESSION['x'] = "this is my value";
?>
<a href="a.php">Click me to see my value!</a>
Now in your a.php file:

Code: Select all

<?php
session_start(); //this is always the first thing at the top of the page you want to use sessions on

echo $_SESSION['x']; //this holds the value of your variable called x

?>

Re: Problem in passing variables through link

Posted: Fri Jul 23, 2010 10:11 pm
by K-Z
Jade wrote:One thing to remember is that a hyperlink can't have spaces or characters in the name otherwise it breaks the href value. You can fix that by putting quotes around the whole href value and by using htmlentities.

Code: Select all

<?php echo "<a href=\"a.php?var=" . htmlentities($x) . "\">link</a></p>"; ?>
If you try to access $x on the a.php page you won't find it because it doesn't exists. However you can get the value that was in x that you passed to the page by doing this:

Code: Select all

<?php
$x = $_GET['var'];

echo $x;
?>
Big picture, if you need a variable to span several pages then you should be using a session like this:

b.php file

Code: Select all

<?php
session_start(); 
$_SESSION['x'] = "this is my value";
?>
<a href="a.php">Click me to see my value!</a>
Now in your a.php file:

Code: Select all

<?php
session_start(); //this is always the first thing at the top of the page you want to use sessions on

echo $_SESSION['x']; //this holds the value of your variable called x

?>
Thank you very much for the reply...You dont know how much you solved my problems.... :D :D :D