How to insert HTML Form Data into a SQL Database Using PHP
HTML forms are a simple and effective way to collect user input such as names, emails, and messages. But to make that data useful, it needs to be stored in a database.
In this tutorial, you'll learn how to insert form data into a MySQL database using PHP ideal for beginners.
Step 1: Create Two Files and a MySQL Table
Create the following two files:
- index.html – for displaying the form
- insert.php – for handling form submission
Important: Place both files in the same folder. Also, keep in mind that filenames like insert.php
are case-sensitive on most hosting servers.
Then, create your database and table using the SQL below:
CREATE DATABASE form_data_db;
USE form_data_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
message TEXT
);
Explanation:
form_data_db
: Your database name.users
: Table to store form data.id
: Auto-increment primary key.name
,email
,message
: Fields to save input.
Step 2: Paste the Code Below into index.html
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h2>Contact Form</h2>
<form action="insert.php" method="POST">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Message:</label><br>
<textarea name="message"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
<form action="insert.php" method="POST">
: Sends form data toinsert.php
.name="..."
: Assigns keys used by PHP to access submitted values.required
: Ensures the user can't submit empty name/email.
Step 3: Paste the Code Below into insert.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'form_data_db';
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO users (name, email, message) VALUES ('$name', '$email', '$message')";
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Explanation:
mysqli_connect()
: Connects to the database.$_POST
: Retrieves submitted form data.INSERT INTO ...
: SQL command to store data.mysqli_query()
: Executes the SQL insert query.mysqli_close()
: Closes the database connection.
Final Notes
You've now created a working HTML form that inserts data into a MySQL database using basic PHP. This is useful for contact forms, feedback forms, and more.
Reminder: This tutorial is for learning purposes. For production environments, always use input sanitization or prepared statements to avoid SQL injection.
For more web development tutorials, visit Coder Sikarwar.