使用php会话跨越2页的变量

时间:2014-03-09 16:31:48

标签: php variables session

我是php新手并学习使用会话。

我试图将来自page1的两个变量(用户输入)转换为page2以在sql查询中使用。

第1页:

<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['Year'] = $_POST['Year'];
$_SESSION['Term'] = $_POST['Term'];
}
include("includes/header.html");
include("includes/navbar.html");

echo "Year = " . $_SESSION['Year'];
echo "Term = " . $_SESSION['Term'];
?>

<div class="main body"> 

<center>
<form action="view_year.php" method="post">
<table border="0">
<tr>
<td>What Year would you like to view?:</td>
<td><input type="text" name="Year" value="YYYY e.g. 2014"></td>
</tr>
<tr>
<td>What Term would you like to view?:</td>
<td><input type="text" name="Term" value="Term1 OR Term2 OR Term3"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</center>

</div>

2页:

<?php
session_start();
$year = $_SESSION['Year'];
include("includes/header.html");
include("includes/navbar.html");

echo " The year is " . $year;
?>

在第1页上,会话变量的设置有效,并且它回显了Year =用户输入的内容,但在第二页上再次使用时却没有。

我错过了一些简单的事情:P?

谢谢你们!

1 个答案:

答案 0 :(得分:0)

如果您未检查$_SESSION['Year'] - var是否实际发送,可能会覆盖$_POST

尝试:

if(isset($_POST['Year'])){
    $_SESSION['Year'] = $_POST['Year'];
    $_SESSION['Term'] = $_POST['Term'];
}