php - 如何在另一个页面中保存用户输入而不覆盖 PHP 中以前的用户输入
问题描述
我想在 PHP 的另一个页面中保存多个用户信息。我有一个表单,用户可以在其中输入一些信息,例如姓名、城市……等等,我想将这些信息保存在表格中。
我使用过会话,但它会覆盖以前的记录。
h3>Contact Form</h3>
<div class="container">
<form method="post" >
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="country">Country</label>
<select id="country" name="country">
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
其他页面.php
<?php
session_start();
$name=$_SESSION['name'];
?>
<h2>HTML Table</h2>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td><?php echo $name ?> </td>
<td></td>
<td></td>
</tr>
</table>
解决方案
会话用于存储临时时间段的值。这是在会话中保存表单数据的方法。以后你可以在你想要的地方取到它。
HTML
<form action="other_page.php" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="mobile">
<button type="submit" name="submit">Submit</button>
</form>
PHP (other_page.php)
<?php
session_start();
if(isset($_REQUEST['submit'])){
$_SESSION['name'] = $_POST['name'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['mobile'] = $_POST['mobile'];
}
?>
如何以 HTML(other_page.php 或其他)获取会话中存储的数据
<h1><?php echo $_SESSION['name'];?></h1>
<h1><?php echo $_SESSION['email'];?></h1>
<h1><?php echo $_SESSION['mobile'];?></h1>
“我使用过会话,但它覆盖了以前的记录”。
精确的。$_SESSION['name'] = $_POST['name']每次提交表单时为 $_SESSION['name'] 设置一个新值。
如果您希望数据具有持久性,则必须将其存储在数据库中。
下一步(other_page.php)
例如,假设您已配置到 bdd mysql 服务器的连接。
<?php
//Initializing the session
session_start();
//writing MySQL Query to insert the details
$insert_query = 'insert into yourtable(
name,
email,
mobile
) values (
' . $_POST['name'] . ",
" . $_POST['email'] . ",
" . $_POST['mobile'] . ",
);"
//let's run the query
mysql_query($insert_query);
?>
推荐阅读
- haskell - 如何为 Shake 规则或操作编写“单元”测试?
- docker - Dockerfile, sbt-assembly - 是否可以在 dockerfile 中使用 sbt-assembly?
- c++ - 在OpenGL中将笛卡尔世界坐标转换为球面局部坐标
- google-analytics - 使用 gtag.js 与 analytics.js 相同的功能
- python - sparsity.PolynomialDecay() TensorFlow 2.0 基于幅度的权重修剪中的 initial_sparsity 参数
- symfony - 创建新 symfony 项目时出错,无法使用 bin/console
- angular - 模态控制器不会生成带有“加载块 N 失败”的模态
- jms - Logstash-Plug in-JMS 和 Weblogic 12.2.1 的问题
- python - 有没有办法清理这个结构?
- visual-studio-code - 使用两种不同类型的代码格式化文件