Skip to main content

Build Newsletter System with PHP and MySQL

The Newsletter or Email Subscription is an important functionality of web applications. It is used in websites to allow visitors to subscribe with their email and get the updates daily or weekly via email.

So if you’re developing a website and wants to implement your Newsletter or Email subscription functionality into your application, then it’s very easy to implement your own email subscription functionality.

In our previous tutorial, you have learned how to build hospital management system with PHP and MySQL. In this tutorial, you will learn how to implement Newsletter or Email subscription system with PHP and MySQL.

Also, read:

We will cover this tutorial with live example. We will implement following functionality:

  • Create email subscription form.
  • Store subscriber details into database.
  • Send verification email link to subscriber.
  • Verify subscriber via email link.

So let’s implement Newsletter System with PHP and MySQL. The major files are:

  • index.php
  • subscribe.js
  • subscription.php
  • verify_subscription.php
  • Subscribe.php: A class contains methods related to subscription.

Step1: Create MySQL Database Table

First we will create MySQL database table subscribers to store subscriber details.

CREATE TABLE `subscribers` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
 `verify_token` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
 `is_verified` tinyint(1) NOT NULL DEFAULT '0',
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

Step2: Create Email Subscription Form

In index.php file, we will create email subscription form with name and email input.

<div class="row">
	<div class="col-lg-12">
		<div class="main-content">
			<div class="susbcribe-container">
				<div class="top">
					<h2>Subscribe Now</h2>
					<h3>Enroll for our <span>free</span> updates</h3>
					<li>We will send you weekly updates</li>
					<li>Get daily articles and latest news</li>
				</div>
				<div class="bottom">							
					<div class="status"></div>						
					<form action="#" id="subscribeForm" method="post">							
						<input type="text" class="form-control" id="name" placeholder="Full Name" required="">	
						<span class="text-danger hidden" id="nameError"></span>
						<input type="email" class="form-control" id="email" placeholder="E-mail" required="">
						<span class="text-danger hidden" id="emailError"></span>
						<input type="button" id="subscribe" value="Subscribe Now">
					</form>
				</div>
			</div>
		</div>
	</div>
</div>	

Step3: Handle Subscription Form Submit

In subscribe.js file, we will handle subscription form submit with validations. We will make ajax request to subscription.php with form values to insert subscription details to database and implement subscription functionality. We will display subscription messages after getting ajax response.

$(document).ready(function() {	
    $('#subscribe').on('click', function() {        
        $('.status').html('');        
        var regEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
        var name = $('#name').val();
        var email = $('#email').val();	        
        if(name.trim() == '' ) {           
			$('#nameError').text('Please enter first and last name.').removeClass('hidden');
			$('#emailError').text('').addClass('hidden');
            $('#name').focus();
            return false;
        } else if(email.trim() == '' ) {          
			$('#emailError').text('Please enter your email.').removeClass('hidden');
			$('#nameError').text('').addClass('hidden');
            $('#email').focus();
            return false;
        } else if(email.trim() != '' && !regEmail.test(email)) {          
			$('#emailError').text('Please enter a valid email.').removeClass('hidden');
			$('#nameError').text('').addClass('hidden');
            $('#email').focus();
            return false;
        } else {            
            $.ajax({
                type:'POST',
                url:'subscription.php',
                dataType: "json",
                data:{subscribe:1, name:name, email:email},
                beforeSend: function () {
                    $('#subscribe').attr("disabled", "disabled");
                    $('.susbcribe-container').css('opacity', '.5');
                },
                success:function(data) {
                    if(data.status == 'ok') {
                        $('#subscribeForm')[0].reset();
                        $('.status').html('<p class="success">'+data.msg+'</p>');
                    } else {
                        $('.status').html('<p class="error">'+data.msg+'</p>');
                    }
                    $('#subscribe').removeAttr("disabled");
                    $('.susbcribe-container').css('opacity', '');
                }
            });
        }
    });
}); 

Step4: Implement Subscription Functionality

In subscription.php file, we will implement email subscription functionality. We will call method $subscriber->getSusbscriber() from class Subscribe.php to check if email already exist otherwise insert new record by calling method $subscriber->insert() class Subscribe.php.

We will create verify token $verifyToken = md5(uniqid(mt_rand())) and then create email message HTML with verify link and send email using mail($email, $subject, $message, $headers) function from PHP. We will return response as JSON data.

<?php 
include_once 'config/Database.php';
include_once 'class/Subscribe.php';

$database = new Database();
$db = $database->getConnection();

$subscriber = new Subscribe($db);

if(isset($_POST['subscribe'])){ 
    $errorMsg = '';     
    $response = array( 
        'status' => 'err', 
        'msg' => 'Something went wrong, please try after some time.' 
    );     
    
    if(empty($_POST['name'])){ 
        $pre = !empty($msg)?'<br/>':''; 
        $errorMsg .= $pre.'Please enter your full name.'; 
    } 
	
    if(empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ 
        $pre = !empty($msg)?'<br/>':''; 
        $errorMsg .= $pre.'Please enter a valid email.'; 
    } 
         
    if(empty($errorMsg)){ 
        $name = $_POST['name']; 
        $email = $_POST['email']; 
        $verifyToken = md5(uniqid(mt_rand()));  
               
		$subscriber->email = $email;
        if($subscriber->getSusbscriber()){ 
            $response['msg'] = 'Your email already exists in our subscribers list.'; 
        } else {        
			
			$subscriber->name = $name;
			$subscriber->verify_token = $verifyToken;
			$insert = $subscriber->insert(); 
             
            if($insert){ 
			
				$siteName = 'Demo Site'; 
				$siteEmail = 'contact@webdamn.com'; 
				 
				$siteURL = ($_SERVER["HTTPS"] == "on")?'https://':'http://'; 
				$siteURL = $siteURL.$_SERVER["SERVER_NAME"].dirname($_SERVER['REQUEST_URI']).'/';
			
                $verifyLink = $siteURL.'verify_subscription.php?email_verify='.$verifyToken; 
                $subject = 'Confirm Subscription'; 
     
                $message = '<h1 style="font-size:22px;margin:18px 0 0;padding:0;text-align:left;color:#3c7bb6">Email Confirmation</h1> 
                <p style="color:#616471;text-align:left;padding-top:15px;padding-right:40px;padding-bottom:30px;padding-left:40px;font-size:15px">Thank you for signing up with '.$siteName.'! Please confirm your email address by clicking the link below.</p> 
                <p style="text-align:center;"> 
                    <a href="'.$verifyLink.'" style="border-radius:.25em;background-color:#4582e8;font-weight:400;min-width:180px;font-size:16px;line-height:100%;padding-top:18px;padding-right:30px;padding-bottom:18px;padding-left:30px;color:#fffffftext-decoration:none">Confirm Email</a> 
                </p> 
                <br><p><strong>'.$siteName.' Team</strong></p>'; 
                 
                $headers = "MIME-Version: 1.0" . "\r\n";  
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";  
                $headers .= "From: $siteName"." <".$siteEmail.">"; 
                 
                $mail = mail($email, $subject, $message, $headers); 
                if($mail){ 
                    $response = array( 
                        'status' => 'ok', 
                        'msg' => 'A verification link has been sent to your email address, please check your email and verify.' 
                    ); 
                } 
            } 
        } 
    } else { 
        $response['msg'] = $errorMsg; 
    }       
    echo json_encode($response); 
} 

We will implement method insert() in class Subscribe.php to insert user subscription details with name, email and verify token.

public function insert(){
		
	if($this->name && $this->email && $this->verify_token) {

		$stmt = $this->conn->prepare("
		INSERT INTO ".$this->subscribersTable."(`name`, `email`, `verify_token`)
		VALUES(?,?,?)");
	
		$this->name = htmlspecialchars(strip_tags($this->name));
		$this->email = htmlspecialchars(strip_tags($this->email));
		$this->verify_token = htmlspecialchars(strip_tags($this->verify_token));					
		
		$stmt->bind_param("sss", $this->name, $this->email, $this->verify_token);
		
		if($stmt->execute()){
			return true;
		}		
	}
}

Step5: Implement Verify Email

In verify_subscription.php file, we will check for email_verify and implement functionality to very email. We will call method $subscriber->verifyToken() from class Subscribe.php to very for valid verify token. We will call method $subscriber->update() to update the email verify status.

<?php 
include_once 'config/Database.php';
include_once 'class/Subscribe.php';

$database = new Database();
$db = $database->getConnection();

$subscriber = new Subscribe($db);
$statusMsg = '';
if(!empty($_GET['email_verify'])){     
	$verifyToken = $_GET['email_verify']; 	
	$subscriber->verify_token = $verifyToken;
    if($subscriber->verifyToken()){ 
       	$subscriber->is_verified = 1;        
        if($subscriber->update()) { 
            $statusMsg = '<p class="success">Your email address has been verified successfully.</p>'; 
        } else { 
            $statusMsg = '<p class="error">Some problem occurred on verifying your email, please try again.</p>'; 
        } 
    } else { 
        $statusMsg = '<p class="error">You have clicked on the wrong link, please check your email and try again.</p>'; 
	}
}
?>

We will implement the method update() in class Subscribe.php to update the is_verified to very the email subscription.

public function update(){
		
	if($this->verify_token) {			
		
		$stmt = $this->conn->prepare("
		UPDATE ".$this->subscribersTable." 
		SET is_verified= ? WHERE verify_token = ?");
 
		$this->verify_token = htmlspecialchars(strip_tags($this->verify_token));
				
		$stmt->bind_param("is", $this->is_verified, $this->verify_token);
		
		if($stmt->execute()){
			return true;
		}
		
	}	
}

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

10 thoughts on “Build Newsletter System with PHP and MySQL

  1. Hi! I’ve added all the files, created the database, and updated the database settings in the Database.php file. The console log shows everything works, but I never receive an email and the database doesn’t update. Do I need to change the “#” to something other than # action=”#” in the form? Thanks in advance for any suggestions on troubleshooting this further.

    1. Please check if mail sending working on your server. may be there issue with mail send on your server. thanks!

  2. Hi. I installed the newsletter. Confirming the newsletter works. But how do I delete the newsletter as a subscriber and how do I admin the newsletter as an admin?

    1. These are not handled in this tutorial, you can add these as per your requirement. thanks!

  3. Having the same issue as DavidE. When you hit submit form just locks up and does nothing. I tried the one on your site and it does what its’ suppose to do.

    1. Check if there are any error while submitting form. Try to debug it. It is working on demo. Thanks!

Comments are closed.