With the widespread use of web applications, forms have become the primary way users input data. Efficiently storing and displaying this data is a critical skill for any web developer. PHP, known for its simplicity and powerful capabilities, is commonly used for handling form submissions.
This article focuses on two key functionalities: how to store form data in a MySQL database and how to display that data on a web page, with complete code examples included.
After a form is submitted, PHP is typically used to capture the submitted data and store it in a database. Here is an example of how to use PHP to insert form data into a MySQL database:
<?php // Database connection configuration $host = "localhost"; $username = "root"; $password = ""; $database = "mydb"; // Connect to database $conn = mysqli_connect($host, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Get form data $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; // Build SQL query $sql = "INSERT INTO form_data (name, email, message) VALUES ('$name', '$email', '$message')"; // Execute query if (mysqli_query($conn, $sql)) { echo "Data stored successfully"; } else { echo "Data storage failed: " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>
This code demonstrates the full process: connecting to the database, retrieving form data via $_POST, constructing an SQL INSERT statement, and executing it. In production, always sanitize inputs to prevent SQL injection.
Once the data is stored, you may want to display it on a web page for review or management. The following PHP example shows how to retrieve and output form data from a MySQL database:
<?php // Database connection configuration $host = "localhost"; $username = "root"; $password = ""; $database = "mydb"; // Connect to database $conn = mysqli_connect($host, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Query the database $sql = "SELECT * FROM form_data"; $result = mysqli_query($conn, $sql); // Display data if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "Name: " . $row['name'] . "<br>"; echo "Email: " . $row['email'] . "<br>"; echo "Message: " . $row['message'] . "<br><br>"; } } else { echo "No data available"; } // Close connection mysqli_close($conn); ?>
This script connects to the database, queries the form_data table, and uses a loop to display each row's data on the web page.
Through the examples above, you’ve seen how to use PHP functions to manage form submissions: inserting submitted data into a MySQL database and retrieving and displaying it on a web page. You can build on this foundation by adding features like input validation, pagination, search functionality, and more to create a robust data management system.