首页 > 解决方案 > 如何在另一个页面中保存用户输入而不覆盖 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>

标签: phpvariablessessionuser-input

解决方案


会话用于存储临时时间段的值。这是在会话中保存表单数据的方法。以后你可以在你想要的地方取到它。

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); 
    ?> 

推荐阅读