[英]Storing form data in session with php
I'm testing a really basic PHP form, where the form data is saved in a session. 我正在测试一个非常基本的PHP表单,该表单数据保存在会话中。 Later, i want that session data to be the default value of the form: 稍后,我希望该会话数据成为表单的默认值:
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="var" value=<?php $name ?>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['var'] = $_POST['var'];
$name = $_SESSION['var'];
}
echo $name;
?>
So, for example if i input "MyName" it should echo "MyName" and in the form there should be the value "MyName". 因此,例如,如果我输入“ MyName”,它应该回显“ MyName”,并且在表单中应该有值“ MyName”。 The problem with the actual code is that it gives an E_NOTICE : type 8 -- Undefined variable: name -- at line 18
error. 实际代码的问题在于它给出了E_NOTICE : type 8 -- Undefined variable: name -- at line 18
出现错误。 I think that the variable is not being stored, can someone help me out on this? 我认为该变量未存储,有人可以帮我吗?
Spotted a few things: 发现了一些东西:
Heres how I'd do it: 这是我的做法:
<?php session_start(); ?>
<strong>Test Form</strong>
<form action="" method="post">
<input type="text" name="var" value="" placeholder="enter name">
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['var'] = $_POST['var'];
}
// Store the session in a variable after the submit - otherwise it will be forgotten on refresh
$name = $_SESSION['var'];
// check if session exists
if(isset($name)) {
echo $name;
}
else {
echo 'no name entered...';
}
?>
You can edit the above to hide the form if a name has been submitted etc. Use session_destroy(); 您可以编辑以上内容以隐藏表单(如果已提交名称等)。使用session_destroy(); to reset the stored session. 重置存储的会话。
Cheers 干杯
The first error I notice is this piece of code: 我注意到的第一个错误是这段代码:
<form action="" method"post">
Where method does not contain the symbol "=" which causes the loss of the parameter post. where方法不包含符号“ =”,这会导致参数发布丢失。 Furthermore, the "session_start ()" function must be placed before any other code. 此外,“ session_start()”函数必须放在任何其他代码之前。 The code derives from this is as follows: 由此得出的代码如下:
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['var'] = $_POST['var'];
$name = $_SESSION['var'];
} else {
$name = null;
}
?>
<strong>Test Form</strong>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="var" value="<?= ($name != null) ? $name : ''; ?>">
<input type="submit" name="Submit" value="Submit!" />
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.