Contact Form with Database
Contact Form with Database
In this lesson, you will build a Contact Form that stores user messages in a database using PHP and MySQL. This is a common feature used in almost every website.
Project Overview
The Contact Form allows users to:
- Submit their name, email, and message
- Store data in the database
- Retrieve and view submitted messages
Database Design
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 1: Create HTML Form
Name: <input type=“text” name=“name”><br>
Email: <input type=“email” name=“email”><br>
Message: <textarea name=“message”></textarea><br>
<input type=“submit” value=“Send”>
</form>
Step 2: Database Connection
$conn = new mysqli(“localhost”, “root”, “”, “test_db”);
if ($conn->connect_error) {
die(“Connection failed”);
}
?>
Step 3: Store Form Data
$name = $_POST[‘name’];
$email = $_POST[’email’];
$message = $_POST[‘message’];
$stmt = $conn->prepare(“INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)”);
$stmt->bind_param(“sss”, $name, $email, $message);
$stmt->execute();
echo “Message sent successfully”;
?>
Step 4: Display Messages
$result = $conn->query(“SELECT * FROM contacts ORDER BY created_at DESC”);
while ($row = $result->fetch_assoc()) {
echo “<h3>” . $row[‘name’] . “</h3>”;
echo “<p>” . $row[‘message’] . “</p>”;
}
?>
Features of the Project
- Collect user messages
- Store data securely in database
- Display submitted messages
- Real-world application feature
Why This Project is Important
Contact forms are essential for communication between users and website owners. This project helps you understand form handling, database storage, and security.
Best Practices
Validate Input
Ensure all fields are correctly filled.
Sanitize Data
Prevent XSS and malicious input.
Use Prepared Statements
Ensure secure database operations.
Start Your Learning Journey
Want to explore more courses like this? click here for free courses
FAQs – Contact Form with Database
What is a contact form
It allows users to send messages through a website.
How is data stored
Using PHP and MySQL database.
Why use prepared statements
To prevent SQL injection.
Can I send emails from this form
Yes, you can integrate email functionality.
Is this used in real websites
Yes, almost every website uses contact forms.



