PHP contact form with MariaDB database storage

In this blog post, I'll show you how to create a PHP contact form that both sends the entered data via email and stores it in a MariaDB database. We'll walk you through the process step by step and include examples to help you get started.

Step 1: Create HTML form

First, you create a simple HTML form that collects user input:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Kontaktformular</title>
</head>
<body>
<h1>Kontaktformular</h1>
<form action="kontaktformular.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br>
<label for="email">E-Mail:</label>
<input type="email" name="email" id="email" required><br>
<label for="message">Nachricht:</label>
<textarea name="message" id="message" required></textarea><br>
<input type="submit" value="Senden">
</form>
</body>
</html>

Step 2: Create PHP script

Create a new file called contactform.php. In this file you write the PHP code that processes the form data and inserts it into the MariaDB database.

First, you establish a connection to the database:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Verbindung fehlgeschlagen: " . $conn->connect_error);
}

Replace your_username, your_password and your_database with your own database credentials.

Next, you process the form data and insert it into the database:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$sql = "INSERT INTO contact_form (name, email, message) VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $name, $email, $message);

if ($stmt->execute()) {
echo "Nachricht erfolgreich gesendet und in der Datenbank gespeichert.";
} else {
echo "Fehler: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
}

$conn->close();

Replace contact_form with the name of your database table that will store the contact form data. Make sure that the table has columns for name, e-mail and message has.

Step 3: Send email

To send the entered data by email, add the following code to the PHP script before inserting the data into the database:

$to = "your_email@example.com";
$subject = "Neue Nachricht vom Kontaktformular";
$headers = "From: " . $email . "\r\n" .
"Reply-To: " . $email . "\r\n" .
"X-Mailer: PHP/" . phpversion();

if (mail($to, $subject, $message, $headers)) {
echo "E-Mail erfolgreich gesendet.";
} else {
echo "E-Mail konnte nicht gesendet werden.";
}

Replace your_email@example.com with your own email address to which the messages should be sent.

Step 4: Add Google reCAPTCHA v2

To add Google reCAPTCHA v2 to your contact form, you must first register your website with Google reCAPTCHA to get a site key and secret key[2]. Then paste the reCAPTCHA code into your HTML form:

<head>
<!-- Weitere Head-Elemente -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<!-- Kontaktformular -->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</body>

Replace your_site_key with your own site key.

Step 5: reCAPTCHA validation in the PHP script

Paste the following code into your contactform.phpscript to validate the reCAPTCHA response before inserting the data into the database and sending the email:

if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
$secretKey = "your_secret_key";
$url = "https://www.google.com/recaptcha/api/siteverify?secret=" . urlencode($secretKey) . "&response=" . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);

if (!$responseKeys["success"]) {
echo "reCAPTCHA-Validierung fehlgeschlagen.";
exit;
}
}

Replace your_secret_key with your own secret key.

Step 6: Add honeypot field

A honeypot field is an invisible field that is filled in by bots but ignored by real users. Insert the following honeypot field into your HTML form:

<input type="text" name="honeypot" id="honeypot" style="display:none;">

Then paste the following code into your contactform.phpscript to check if the honeypot field has been filled in:

if (!empty($_POST["honeypot"])) {
// Honeypot-Feld wurde ausgefüllt, wahrscheinlich ein Bot
exit;
}

Complete!

Now you have a working PHP contact form that emails the entered data, stores it in a MariaDB database, and uses both Google reCAPTCHA v2 and a honeypot field for spam and bot defense. You can customize the form and PHP script as needed to add additional fields or functionality.