简体   繁体   中英

Carrying Variables Between 3 PHP Pages

I am creating a set of 3 pages, each with a dropdown menu. The values from the previous dropdown menus will populate the next dropdown menu. I understand that I must use session variables to hold the value of each dropdown menu into later pages. As a simple test, I echo the variables to see if they have been carried over -- and that's where the problem is.

I have three different files: choose_cc.php, choose_uni.php, and choose_major.php The value from the dropdowm menu in choose_cc.php does get echoed in choose_uni.php -- however the value from choose_cc.php does NOT get carried over into choose_major.php -- despite me storing it into a session variable.

the flow of pages is like this;

choose_cc.php --> choose_uni.php --> choose_major.php Each php file has it's own form. The problem lies in when I try to call the value from choose_cc.php into choose_major.php, i have issues.

The name of the form on choose_cc.php is choose_cc . The name of the form on choose_uni.php is choose_uni .

So for example, in choose_uni.php, I retrieve the value from the dropdown menu on the previous page (choose_cc.php) like this: $_SESSION['choose_cc'] = trim($_GET['choose_cc']); //fetches cc from previous page $user_cc = $_SESSION['choose_cc']; echo $user_cc;

and when I echo it as I did above, it works! Okay perfect!

But when I head onto choose_major.php, I try retrieving the value again from the form, but to no avail like this;

echo $_SESSION['choose_uni']; //this works
echo $_SESSION['choose_cc']; //this doesn't work

I have made sure to store to do session_start() on the beginning of each page as well.

Please help me out! this is driving me insane!

Create a new "see.php" with this:

session_start(); 
print_r($_SESSION);

and execute it after each choose_cc.php, choose_uni.php and choose_major.php to take a look the session you have after you run your programs.

Simple as this:

a) add session_start(); at the beginning of ALL the involved pages. Some weird stuff happens sometimes if you put a space before it, or even a new line. So be sure it is the very first thing in your script.

<?php
session_start();
?>

b) if needed, check the variable to save into session for not empty(); That way you can be sure the session variable contains something, unless of course you want explicitly to be empty.

c) then load the session variable. You can temporary check it with a var_dump();

<?php
session_start();
if (!empty(trim($_GET['choose_cc'])))
{
    $_SESSION['choose_cc'] = $_GET['choose_cc'];
}
var_dump($_SESSION['choose_cc']);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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