You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现表单数据持久化显示及MySQL存储后回显至表单

Hey there! Let's tackle your two form-related questions with practical, actionable code examples that fit your existing HTML structure.

1. Keeping Form Data Persistent and Visible to Users

If you want form inputs to stay filled even after a page refresh (before submission), we can use the browser's localStorage to save values locally. Here's how to implement it:

Step 1: Add JavaScript to Save Inputs to localStorage

Add this script at the bottom of your HTML page (right before </body>):

// Save input values to localStorage as the user types
document.querySelectorAll('input[name]').forEach(input => {
  input.addEventListener('input', function() {
    localStorage.setItem(this.name, this.value);
  });
});

// Populate inputs from localStorage when the page loads
window.addEventListener('load', function() {
  document.querySelectorAll('input[name]').forEach(input => {
    const savedValue = localStorage.getItem(input.name);
    if (savedValue) {
      input.value = savedValue;
    }
  });
});

This will automatically save every input's value as the user types, and load them back when the page refreshes. Note that this data stays only in the user's current browser—if they switch devices, it won't carry over. For cross-device persistence, you'll need to combine this with the backend solution below.

2. Submitting Form Data to MySQL and Echoing It Back

To store data in MySQL and show the submitted values in the form after submission, we'll use a backend language (we'll use PHP here, since it's widely used with MySQL) to handle the database operations and pass data back to the frontend.

Step 2.1: Set Up the MySQL Table

First, create a table in your MySQL database to store submissions. Run this SQL query in your database management tool (like phpMyAdmin):

CREATE TABLE user_submissions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  lastname VARCHAR(255) NOT NULL,
  -- Add other form fields here (e.g., firstname, email)
  submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 2.2: Create the PHP Backend Script (submit-form.php)

This script will handle form submission, insert data into MySQL, and fetch the submitted data to echo back:

<?php
// Database configuration
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_db_username';
$password = 'your_db_password';

// Initialize variables for form values
$lastname = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Sanitize input to prevent XSS
  $lastname = htmlspecialchars($_POST['lastname']);

  // Connect to MySQL using mysqli (prepared statements to prevent SQL injection)
  $conn = new mysqli($host, $username, $password, $dbname);
  
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  // Prepare and execute insert statement
  $stmt = $conn->prepare("INSERT INTO user_submissions (lastname) VALUES (?)");
  $stmt->bind_param("s", $lastname);
  $stmt->execute();

  // Optional: Fetch the latest submission to echo back (in case you want to show the saved data)
  $result = $conn->query("SELECT lastname FROM user_submissions ORDER BY submitted_at DESC LIMIT 1");
  if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $lastname = $row['lastname'];
  }

  $stmt->close();
  $conn->close();
}
?>

Step 2.3: Modify Your HTML Form to Work with the Backend

Update your form to point to the PHP script, and set the value attribute to the backend-provided $lastname variable. Also, combine it with the localStorage script for a seamless experience:

<!-- Add the form tag wrapping your form groups -->
<form method="POST" action="submit-form.php">
  <div class="form-group">
    <label class="control-label col-sm-2" for="lname">Last Name*</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="lastname" placeholder="Last Name" name="lastname" 
             value="<?php echo $lastname; ?>" autocomplete="nope" required>
    </div>
  </div>
  <!-- Add other form fields here, following the same value pattern -->
  
  <!-- Add a submit button -->
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Submit</button>
    </div>
  </div>
</form>

<!-- Include the localStorage script from Step 1 here -->
<script>
// Save input values to localStorage as the user types
document.querySelectorAll('input[name]').forEach(input => {
  input.addEventListener('input', function() {
    localStorage.setItem(this.name, this.value);
  });
});

// Populate inputs from localStorage when the page loads (only if backend didn't set a value)
window.addEventListener('load', function() {
  document.querySelectorAll('input[name]').forEach(input => {
    if (!input.value) { // Only fill if backend didn't provide a value (e.g., first load)
      const savedValue = localStorage.getItem(input.name);
      if (savedValue) {
        input.value = savedValue;
      }
    }
  });
});
</script>

Key Security Notes

  • SQL Injection: We used prepared statements in PHP to prevent malicious SQL input. Never directly insert user input into SQL queries.
  • XSS Protection: We used htmlspecialchars() when echoing the $lastname variable to prevent cross-site scripting attacks.

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:44:57