william
william

Reputation: 117

PHP session lost in the same page?

I'm trying to create a simple search page in PHP.

the page has some $SESSION variables that has been passed through from the Previous page.

when I reach the page (BEFORE searching), the page looks like this: my-page.php

and I have this session variable passed on from the previous page to my-page.php:

         $_SESSION["phone"] = $Cphone ;


         $CUphone = $_SESSION["phone"];

         echo $CUphone;

up to this point everything works fine and I get the echo-ed $CUphone on my-page.php properly.

now, there is a simple search form on my-page.php so I can search mysql database if I wanted to.

like so:

<form action="my-page.php" method="GET">
<input type="text" name="search" placeholder="Search"/>
</form>

and when I search using the form above, I get the results properly too as expected... and the page will become

my-page.php?search=SOMETHING

and the search function works perfectly fine too....

BUT the problem will start from here (the moment I search for something)...

I basically loose echo $CUphone; if the my-page.php becomes my-page.php?search=SOMETHING..

which means I loose the sessions because $CUphone is stored in sessions like i said above.

so is there any way to keep the sessions on my-page.php?search=something ?

any advise would be appreciated.

Upvotes: 1

Views: 1287

Answers (2)

Mubo
Mubo

Reputation: 1070

I think you need to check if the session is already set or not.

//That variable should be set an not empty
if (isset($Cphone) && !empty($Cphone)){

    $_SESSION["phone"] = $Cphone ;

    //To check first if the session is set or not
    if(isset($_SESSION['phone'])){

        $CUphone = $_SESSION["phone"];

        echo $CUphone;
    }

}else{

    echo 'session not set';
}

in that case, you will either get an error to trace, which comes from the variable or it will work.

Upvotes: 0

EternalHour
EternalHour

Reputation: 8651

You need to add a condition when setting the session variable.

session_start();

if($Cphone) {
    $_SESSION["phone"] = $Cphone;
} else {
    echo "phone number does not exist";
}

if($_SESSION["phone"]) {
    $CUphone = $_SESSION["phone"];
} else {
    echo "session does not exist";
}

It's best to set your session variables only one time unless there is a good reason to change them. This is a very basic recommendation not knowing anything about your application. But it's best to make your condition as specific as possible.

Upvotes: 4

Related Questions