我有两页,A和B.
我想在B中回显一个用A编写的变量。
这是第一页:
<?php session_start(); ?>
<html>
<head>
<title>Registration Form - 1 of 2</title>
</head>
<body>
<h1>Registration - Part 1 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<form action="registerFormTwo.php" method="post">
First Name:<input type="text" name="firstName" /><br /><?php $_SESSION['firstName'] = firstName; ?>
Last Name:<input type="text" name="lastName" /><br /><?php $_SESSION['lastName'] = lastName; ?>
Age:<input type="text" name="age" /><br /><?php $_SESSION['age'] = age; ?>
Date of Birth:<input type="text" name="dateOfBirth" /><br /><?php $_SESSION['dateOfBirth'] = dateOfBirth; ?>
<input type="submit" />
</form>
</body>
这是第二个:
<?php session_start(); ?>
<html>
<head>
<title>Registration Form - 2 of 2</title>
</head>
<body>
<h1>Registration - Part 2 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<?php //wrote this in just to test that session information is saving, but it isn't.
echo $_SESSION['name']; ?>
<form action="registerFinish.php" method="post">
Nationality<input type="text" name="nationality" /><br /><?php $_SESSION['nationality'] = nationality; ?>
Profession:<input type="text" name="profession" /><br /><?php $_SESSION['profession'] = profession; ?>
<input type="submit" />
</form>
</body>
在第二页上,应该回显名称变量,但不显示任何内容。
感谢您的帮助。
修改
这是formOne上的代码,它仍然无效:
<?php session_start();
if ($_POST) {
// Store our name in the session array
$_SESSION["firstName"] = $_POST["firstName"];
}
?>
<html>
<head>
<title>Registration Form - 1 of 2</title>
</head>
<body>
<h1>Registration - Part 1 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<form action="registerFormTwo.php" method="post">
First Name:<input type="text" name="firstName" /><br />
Last Name:<input type="text" name="lastName" /><br /><?php $_SESSION['lastName'] = lastName; ?>
Age:<input type="text" name="age" /><br /><?php $_SESSION['age'] = age; ?>
Date of Birth:<input type="text" name="dateOfBirth" /><br /><?php $_SESSION['dateOfBirth'] = dateOfBirth; ?>
<input type="submit" />
</form>
</body>
</html>
答案 0 :(得分:2)
表单数据不会直接进入$_SESSION
。你必须把它放在那里。由于您的表单method
是POST,因此您可以从服务器端的$_POST
中提取数据:
session_start();
if ($_POST) {
// Store our name in the session array
$_SESSION["name"] = $_POST["name"];
}
如果您只是想在表单提交失败时保留表单中的值,则不需要使用会话。您可以将$_POST
中的值直接重新打印到标记中:
<input type="text" name="name" value="<?php print $_POST["name"]; ?>" />
请注意,所有这些都发生在您发布到的页面上。如果您的第一个表单位于page1.php
,那么您将忽略所有这些。如果您从page1.php
发布到page2.php
,则可以将上述代码放在page2.php
上。
<强>更新强>
我刚注意到表格元素旁边的以下内容:
<?php $_SESSION['lastName'] = lastName; ?>
lastName
在此不代表任何内容。 $_POST["lastName"]
代表发布的数据。如果您尝试打印上次提交的值,我会这样做:
<?php print $_POST["lastName"]; ?>