Skip to content
PHP Logo

What are common methods for storing user input from a form in a database using PHP?

When a user submits a form on a website, PHP can be used to store the input data into a database for future retrieval or analysis. One common method for achieving this is by using SQL queries to insert the form data into a database table. By sanitizing and validating the user input before storing it in the database, we can ensure data integrity and security.

php
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Sanitize input data
$name = mysqli_real_escape_string($conn, $name);
$email = mysqli_real_escape_string($conn, $email);
$message = mysqli_real_escape_string($conn, $message);

// Insert form data into database
$sql = "INSERT INTO form_data (name, email, message) VALUES ('$name', '$email', '$message')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close database connection
$conn->close();
?>