Email subscriptions are a common feature on many websites, allowing users to receive updates, newsletters, or promotions by submitting their email addresses. This tutorial walks you through creating a simple and functional PHP-based subscription system, including database setup, form handling, and email notifications.
First, create a database table named subscribers to store user subscription data. The table should include the following fields:
Use the SQL command below to create the table:
CREATE TABLE subscribers ( id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Next, add a simple subscription form to your website, allowing users to enter their email address and submit the form:
<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 subscribe.php file to process form submissions. This script will:
<?php // Connect to the database $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 email notifications."); } // Insert 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 welcome message using PHP’s built-in mail() function:
// Send welcome email $to = $email; $subject = "Thank you for subscribing!"; $message = "We're glad to have you on board. Stay tuned for updates!"; $headers = "From: your_email@example.com"; mail($to, $subject, $message, $headers);
Make sure to replace the email address in the $headers variable with your own.
By following the steps above, you can quickly build a basic yet effective email subscription feature using PHP. This functionality helps retain users and provides a valuable channel for future communication and marketing.