Jump to content

Unable get values from $_SESSION, error msg is Notice: Undefined variable: _SESSION


Recommended Posts

First let me explain my code.
It comprises of three php files.

  • inc_fn_header_and_menu.php,  contains the HTML and CSS header details and it initializes the session via session_start();

 

  • This  is later included in project_status.php] .

 

  • In project_status.php] , I have included another file project_status_app.php which contains a HTML form.


 project_status.php:

<?php
 include 'inc_fn_header_and_menu.php';
function includeFile($file,$variable) {
    $var = $variable;
    include($file);
}
if (isset($_GET['id']) && $_GET['id']!="") {
    $pid    = $_GET['id'];
    $_SESSION['pidForApproval'] = $_GET['id'];
    $query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
    $result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n" . mysqli_error());
    foreach ($result as $row) {
        $status = $row['status'];
    }        
}
...........some PHP and HTML code.......
	<div id="customerPurchaseApprovalForm">
<?php  
  echo '<p>APPROVAL FOR CUSTOMER PURCHASE</p>';
  $discountApprovalStatus = "Granted";
  if ($discountApprovalStatus == "Granted") {  
 
  includeFile("project_status_app.php",$highestannualvalue);
  } else {
     //.........
  }

In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array.

<?php
        // put your code here  UPDATE `pp` SET `customer_purchase_remarks` = 'hahaha' WHERE `pp`.`id` = 207;
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            include '../../inc/fastlogin.php';      
            $sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'"; 
            $result = mysqli_query ( $fastdb, $sql ) ;
            if (mysqli_affected_rows($fastdb) != 1) { 
               $_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>";
                //echo "<p>Error while updating WHERE id='{$_POST['pidForApproval']}'</p>".mysqli_error($fastdb);                 
            } else { 
                $_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>";
                //echo "Records was updated successfully."; 
            }
            header ("location: project_status.php?id="$_SESSION['pidForApproval']);
            exit();
        }    
        
        ?>

When I load  project_status.php,  project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the 

header ("location: project_status.php?id=".$_SESSION['pidForApproval']);


I suspected that my $_SESSION['pidForApproval'] is not being populated in project_status.php but I echoed back $_SESSION['pidForApproval'] in that file itself and I can see it is being populated. Hence, I suspect that the $_SESSION['pidForApproval'] is not being passed to project_status_app.php. I have already attempted to include session_start(); clause in project_status_app.php but that gives an error, stating that the session has already started, in inc_fn_header_and_menu.php. Can someone help me as to why the $_SESSION['pidForApproval'] is not being passed on to the project_status_app.php file. Thank you.

Edited by Robinson
Missing some information.
Link to post
Share on other sites

i think (i cannot tell for sure without having all the code and actual testing, because of how overly complicated this code is) your issue is due to how your code is laid out (your form processing code is inside the html document), that you are not validating inputs w/user error messages for 'required' values, have too many variables being copied to other variables, too many database connections, and that you are using session variables when they are not needed. you need to Keep It Simple (KISS.)

your code needs to ALWAYS validate inputs before using them, setting up validation errors for the visitor for 'required' inputs. doing this would at least help you find where the problem starts at and will eliminate follow-on errors that aren't directly due to the actual problem. the session variable in question IS an input to your page and needs to be validated before use.

the code for any page should be laid out in this general order -

  1.  initialization - define, require, create, ... things your page needs, such as the session_start() statement, a database connection, configuration values, ...
  2. post method form processing code - a post method form should be used for things that create/update data on the server or perform an action such as sending an email.
  3. get method business logic - get/create data needed to display the dynamic content on the web page.
  4. html document/template - using simple php code or an actual template system, produce the actual html document, using the data produced from the above sections of code.

lastly, don't put external, unknown, dynamic values directly into sql query statements. use prepared queries.

 

Edited by mac_gyver
Link to post
Share on other sites

1. There is a syntax error in what you posted for project_status_app.php. What's your real code?
2. Don't use the session to shuffle short-lived data between pages like this. You already have a (weird) mechanism to give data to another file. Use that for the pidForApproval too.

Link to post
Share on other sites
2 hours ago, requinix said:

1. There is a syntax error in what you posted for project_status_app.php. What's your real code?
2. Don't use the session to shuffle short-lived data between pages like this. You already have a (weird) mechanism to give data to another file. Use that for the pidForApproval too.

By "a (weird) mechanism ", I assume you mean these lines:
 

function includeFile($file,$variable) {    
 $var = $variable;     
 include($file); 
}

Could get rid of this line and the pidForApproval can get passed into the included file automatically? Is it advisable? Thanks.

Link to post
Share on other sites

It's weird because... ah, well, doesn't matter that much.

Yes, you can include() a file wherever you want and it will have access to all the same variables at that point. It will have $discountApprovalStatus (set a couple lines earlier) and $highestannualvalue (don't know where that's coming from but apparently it exists). It also has $_GET and $_SESSION and all the other "superglobal" variables that are already available to everyone, everywhere.

But, and this is going to take a fair bit of work but I promise it's worth it,

You're touching on a good design pattern that not many people ever hear about, let alone know. This one is called "MVP". It's like MVC (if you've heard of that) but works in a slightly different way. The key is that you have two places with code: one that does display (project_status.php) and one that has processing logic (project_status_app.php).

One big change that you should make is that the app.php should not simply run everything inside it. You should use it as a place to store functions. For example, a function that handles updating the remarks in the database. This function does not check REQUEST_METHOD or grab values from $_POST. It takes all the values it needs as function parameters. Looks like

function updateRemarks($remarkstxt, $pidForApproval) {

What does the form send data to? It submits to the same file that started this process: project_status.php. That file is where you put the stuff about REQUEST_METHOD and $_POST.

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	include('project_status_app.php');

	updateRemark($_POST['remarkstxt'], $_SESSION['pidForApproval']);

  	// updateRemark should only update the remark - it shouldn't care about doing redirects too
	header("Location: project_status.php?id=" . $_SESSION['pidForApproval']);
	exit();
}

include 'inc_fn_header_and_menu.php';
// ...

With that updated, there's one more set of changes to make: not using $_SESSION, like I complained about earlier.

And it's really, really easy. The pidForApproval is coming from $_GET to start with, right? Just keep doing that. Have the form submit to project_status.php?id=$pid and inside your new if block (seen above) you grab the pid from $_GET once more. Better yet, you can merge some of the new code with some of the old code:

<?php

if (isset($_GET['id']) && $_GET['id']!="") {
	$pid = $_GET['id'];
	$query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
	$result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n" . mysqli_error());
	foreach ($result as $row) {
		$status = $row['status'];
	}

	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		include('project_status_app.php');

		updateRemark($_POST['remarkstxt'], $pid);

		header("Location: project_status.php?id=" . $pid);
		exit();
	}
}

include 'inc_fn_header_and_menu.php';
// ...

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.