Email subscription is a common feature for websites aiming to engage users through newsletters, updates, or promotional messages. In this tutorial, you’ll learn how to create a simple and functional email subscription system using PHP, including database structure, form handling, and email notifications.
Start by creating a database table to store the subscription information. The table should include an auto-increment ID, the user’s email address, and a timestamp of when the subscription occurred.
CREATE TABLE subscribers ( id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
On your website, add a form that allows users to submit their email addresses to subscribe:
<form action="subscribe.php" method="post"> <input type="email" name="email" placeholder="Enter your email address" required> <button type="submit">Subscribe</button> </form>
Create a PHP file named subscribe.php to handle the form submission. The script should:
Here’s a complete example:
<?php // Database connection settings $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database"; $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Database connection failed: " . $conn->connect_error); } // Get the submitted email $email = $_POST['email']; // Validate email format if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { die("Please enter a valid email address"); } // Check for existing subscription $sql = "SELECT id FROM subscribers WHERE email='$email'"; $result = $conn->query($sql); if ($result->num_rows > 0) { die("You have already subscribed to our mailing list"); } // Insert the new subscriber $sql = "INSERT INTO subscribers (email) VALUES ('$email')"; if ($conn->query($sql) === TRUE) { echo "Subscription successful!"; } else { echo "Subscription failed: " . $conn->error; } $conn->close(); ?>
After a successful subscription, you can send a confirmation email using PHP’s built-in mail() function:
<?php // Send a confirmation email $to = $email; $subject = "Thank you for subscribing!"; $message = "We appreciate your subscription to our newsletter."; $headers = "From: your_email@example.com"; mail($to, $subject, $message, $headers); ?>
Make sure to replace the sender's email with your own valid address.
By following the steps above, you can easily integrate a basic email subscription system into your website. This guide covers everything from database setup to sending confirmation emails, and can be extended later to include features like unsubscribe options, email templates, and segmented mailing lists.