Passing PHP Variable From One Dynamic Page to Another

我只是一个虾纸丫 提交于 2019-12-02 15:37:26

问题


I am trying to pass on some variables using SESSION from one PHP page to the next.

The first page contains this code and after the user clicks submit, it goes to Page 2:

<!--SESSIONS TO PASS ON VARIABLES-->
<?php $_SESSION['file'] = $file; ?>
<?php $_SESSION['linecount'] = $linecount; ?>
<?php $_SESSION['priceperpost'] = $priceperpost; ?>
<?php $_SESSION['totalcost'] = $totalcost; ?>
<!--//SESSIONS TO PASS ON VARIABLES-->

And this is what I have on the next page, Page 2, after the form is submitted:

<!--VARIABLES FROM PREVIOUS PAGE-->
<?php $file = $_SESSION['file']; ?>
<?php $linecount = $_SESSION['linecount']; ?>
<?php $priceperpost = $_SESSION['priceperpost']; ?>
<?php $totalcost = $_SESSION['totalcost']; ?>
<!--//VARIABLES FROM PREVIOUS PAGE-->  

But it is not getting the code because I am trying to echo the variables on Page 2:

  <u>Number of Posts:</u> <?php echo ($linecount); ?><br>
  <br>
  <u>Price Per Post:</u> $<?php echo ($priceperpost); ?> <br>
  <u>Total Cost:</u> $<?php echo ($totalcost); ?><br>
  <br>

Please help as I do not know what I am doing wrong, any help would be greatly appreciated.

Yes I have also called session_start

Here is the updated code:

 <?php 
session_start(); 
$_SESSION['file'] = $file;
$_SESSION['linecount'] = $linecount;
$_SESSION['priceperpost'] = $priceperpost;
$_SESSION['totalcost'] = $totalcost; 
?>

and on the next page

<?php
session_start();
$file = $_SESSION['file'];
$linecount = $_SESSION['linecount'];
$priceperpost = $_SESSION['priceperpost'];
$totalcost = $_SESSION['totalcost']; 
?>

回答1:


Make sure that you are starting your session before creating the variables and before calling them back :

session_start();



回答2:


Are you sure your variables are set i.e. $totalcost? A comment on your code. Unless, you are breaking in and out of PHP and HTML, you do not need to open and close PHP on every line.

This can be rewritten:

<!--SESSIONS TO PASS ON VARIABLES-->
<?php $_SESSION['file'] = $file; ?>
<?php $_SESSION['linecount'] = $linecount; ?>
<?php $_SESSION['priceperpost'] = $priceperpost; ?>
<?php $_SESSION['totalcost'] = $totalcost; ?>
<!--//SESSIONS TO PASS ON VARIABLES-->

As:

<?php
// SESSIONS TO PASS ON VARIABLES
session_start();
$_SESSION['file'] = $file;
$_SESSION['linecount'] = $linecount;
$_SESSION['priceperpost'] = $priceperpost;
$_SESSION['totalcost'] = $totalcost; 
// SESSIONS TO PASS ON VARIABLES
?>


来源:https://stackoverflow.com/questions/14147335/passing-php-variable-from-one-dynamic-page-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!