Build a Newsletter Email Subscription with PHP and MySQL
Newsletter marketing is a form of direct-to-consumer advertising. This is used by companies that want to send information directly to valuable and existing customers. A Newsletter subscription is the most important part of the dynamic web application. An email subscription provides an option for visitors to receive updated new stuff via email. The most web application provides an email subscription option that allows site visitors to get updates daily, weekly, monthly, and yearly newsletter from the web application.
In this tutorial, we will learn how to Build a Newsletter Email Subscription with PHP and MySQL, jQuery and Ajax. This is a very simple example; you can just copy-paste and change according to your requirement.
Before started to implement the Newsletter Email Subscription with PHP and MySQL, look files structure:
- newsletter-email-subscription-with-php-mysql
- assets
- css
- style.css
- images
- css
- class
- DBConnection.php
- Newsletter.php
- templates
- header.php
- footer.php
- action.php
- index.php
- assets
Step 1: Create the database and Table
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE `newsletter` ( `id` int(11) NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `verification_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `is_verified` int(1) NOT NULL DEFAULT 0, `created_date` datetime NOT NULL, `modified_date` datetime NOT NULL DEFAULT current_timestamp(), `status` int(1) NOT NULL DEFAULT 1 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ALTER TABLE `newsletter` ADD PRIMARY KEY (`id`); ALTER TABLE `newsletter` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; |
Step 2: Database Connection class
Create a file named DBConnection.php inside “class/” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * @package DBConnection * * @author TechArise Team * * @email info@techarise.com * */ // Database Connection class DBConnection { private $_dbHostname = "localhost"; private $_dbName = "demo_DB"; private $_dbUsername = "root"; private $_dbPassword = ""; private $_con; public function __construct() { try { $this->_con = new PDO("mysql:host=$this->_dbHostname;dbname=$this->_dbName", $this->_dbUsername, $this->_dbPassword); $this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } // return Connection public function returnConnection() { return $this->_con; } } ?> |
Step 3: Create a class file
Create a class file named Newsletter.php inside “class/” folder.
- The class handles the Newsletter process.
__construct()
– Loads the required class.create()
– Insert recored in databaseupdate()
– Update record in databasedelete()
– Delete record from database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
<?php /** * @package Newsletter class * * @author TechArise Team * * @email info@techarise.com * */ // include connection class include("DBConnection.php"); // Event class Newsletter { protected $db; private $_name; private $_email; private $_verifyCode; private $_isVerified; private $_createdDate; private $_modifiedDate; private $_status; public function setName($name) { $this->_name = $name; } public function setEmail($email) { $this->_email = $email; } public function setVerifyCode($verifyCode) { $this->_verifyCode = $verifyCode; } public function setIsVerified($isVerified) { $this->_isVerified = $isVerified; } public function setStatus($status) { $this->_status = $status; } // __construct public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // create record in database public function create() { try { $sql = 'INSERT INTO newsletter (name, email, verification_code, is_verified, created_date, status) VALUES (:name, :email, :verification_code, :is_verified, :created_date, :status)'; $data = [ 'name' => $this->_name, 'email' => $this->_email, 'verification_code' => $this->_verifyCode, 'is_verified' => $this->_isVerified, 'created_date' => date('Y-m-d H:i:s', time()), 'status' => $this->_status, ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $this->db->lastInsertId(); return $status; } catch (Exception $err) { die("Oh noes! There's an error in the query! ".$err); } } // update record in database public function update() { try { $sql = "UPDATE newsletter SET is_verified=:is_verified, status=:status WHERE verification_code=:verification_code"; $data = [ 'is_verified' => $this->_isVerified, 'status' => $this->_status, 'verification_code' => $this->_verifyCode, ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $err) { die("Oh noes! There's an error in the query! " . $err); } } // get data from database public function getRow() { try { $sql = "SELECT verification_code FROM newsletter WHERE email=:email"; $stmt = $this->db->prepare($sql); $data = [ 'email' => $this->_email ]; $stmt->execute($data); $result = $stmt->fetch(\PDO::FETCH_ASSOC); return $result; } catch (Exception $err) { die("Oh noes! There's an error in the query!" .$err); } } // delete record from database public function delete() { try { $sql = "DELETE FROM newsletter WHERE verification_code=:verification_code"; $stmt = $this->db->prepare($sql); $data = [ 'verification_code' => $this->_verifyCode ]; $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $err) { die("Oh noes! There's an error in the query! " . $err); } } } ?> |
Step 4: Create action file named
action.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
<?php // include event class include_once 'class/Newsletter.php'; // create obj $subscribe = new Newsletter(); // post method $post = $_POST; $get = $_GET; // define array $json = array(); $site_url = 'https://techarise.com/demos/php/newsletter-email-subscription-with-php-mysql/'; $site_name = 'TechArise'; $site_email = 'info@techarise.com'; // create record in database if(!empty($post['action']) && $post['action']=="create") { $name = $post['name']; $email = $post['email']; // generate verification code $verification_code = md5(uniqid(mt_rand())); if(empty(trim($name))){ $json['error']['name'] = 'Please enter first name'; } if(empty(trim($email))){ $json['error']['email'] = 'Please enter email address'; } if (validateEmail($email) == FALSE) { $json['error']['email'] = 'Please enter valid email address'; } $subscribe->setEmail($email); // exist Row $existRow = $subscribe->getRow(); if($existRow > 0) { $json['error']['email'] = 'Your email already exists in our subscribers list.'; } if(empty($json['error'])){ $subscribe->setName($name); $subscribe->setEmail($email); $subscribe->setVerifyCode($verification_code); $subscribe->setIsVerified(0); $subscribe->setStatus(0); $status = $subscribe->create(); // Verification email configuration $subscribe = urlencode(base64_encode($verification_code.'|subscribe')); $subscribeLink = $site_url.'action.php?subscribe='.$subscribe; // unsubscribe link $unsubscribe = urlencode(base64_encode($verification_code.'|unsubscribe')); $unsubscribeLink = $site_url.'action.php?unsubscribe='.$unsubscribe; $subject = 'Confirm Subscription'; $bodyMsg = '<h1 style="font-size:20px;margin:20px 0 0;padding:0;text-align:left;color:#273E4A">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 '.$site_name.'! Please confirm your email address by click the link below.</p> <p style="text-align:center;"> <a target="_blank" href="'.$subscribeLink.'" style="border-radius:5px;background-color:#273E4A;font-weight:bold;min-width:170px;font-size:14px;line-height:100%;padding-top:15px;padding-right:30px;padding-bottom:15px;padding-left:30px;color:#ffffff;text-decoration:none" rel="noopener noreferrer">Confirm Email</a> </p> <br><p><strong>'.$site_name.' Team</strong></p> <br><p><a style="color:#ccc; font-size:12px;" target="_blank" href="'.$unsubscribeLink.'" rel="noopener noreferrer">Unsubscribe</a></p>'; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= "From: $site_name"." <".$site_email.">"; // Send verification email $mailStatus = mail($email, $subject, $bodyMsg, $headers); if($mailStatus) { $json['status'] = 'mail_sent'; } $json['msg'] = 'success'; $json['newsletter_id'] = $status; } else { $json['msg'] = 'failed'; $json['newsletter_id'] = ''; } header('Content-Type: application/json'); echo json_encode($json); } // update record in database if(!empty($get['subscribe'])) { $getURIData = explode('|', urldecode(base64_decode($get['subscribe']))); $verification_code = $getURIData[0]; $subscribe->setVerifyCode($verification_code); $subscribe->setIsVerified(1); $subscribe->setStatus(1); $status = $subscribe->update(); if(!empty($status)){ $json['msg'] = 'Your email address has been verified successfully'; } else { $json['msg'] = 'Some problem occurred on verifying your account, please try again'; } include('templates/header.php'); ?> <section class="showcase"> <div class="container"> <div class="text-center"> <h1 class="display-3">Thank You!</h1> <?php if(!empty($json['msg'])) { ?> <p class="lead"><?php print $json['msg']; ?></p> <?php } ?> <hr> <p> Having trouble? <a href="mailto:info@techarise.com">Contact us</a> </p> <p class="lead"> <a class="btn btn-primary btn-sm" href="<?php print $site_url;?>" role="button">Continue to homepage</a> </p> </div> </div> </section> <br><br><br><br><br><br> <?php include('templates/footer.php');; } // delete record from database if(!empty($get['unsubscribe'])) { $getURIData = explode('|', urldecode(base64_decode($get['unsubscribe']))); $verification_code = $getURIData[0]; $subscribe->setVerifyCode($verification_code); $status = $subscribe->delete(); if(!empty($status)){ $json['msg'] = 'Newsletter unsubscribe successfully'; } else { $json['msg'] = 'Some problem occurred on verifying your account, please try again'; } include('templates/header.php'); ?> <section class="showcase"> <div class="container"> <div class="text-center"> <h1 class="display-3">Unsubscribe</h1> <?php if(!empty($json['msg'])) { ?> <p class="lead"><?php print $json['msg']; ?></p> <?php } ?> <hr> <p> Having trouble? <a href="mailto:info@techarise.com">Contact us</a> </p> <p class="lead"> <a class="btn btn-primary btn-sm" href="<?php print $site_url;?>" role="button">Continue to homepage</a> </p> </div> </div> </section> <br><br><br><br><br><br> <?php include('templates/footer.php'); } // check email validation function validateEmail($email) { return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE; } ?> |
jQuery code handle AJAX request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
jQuery(document).on('click', 'button#subscribe-newsletter', function() { jQuery.ajax({ type:'POST', url:'action.php', data:jQuery("form#newsletter-frm").serialize(), dataType:'json', beforeSend: function () { jQuery('button#subscribe-newsletter').button('Loding..'); }, complete: function () { jQuery('button#subscribe-newsletter').button('reset'); setTimeout(function () { jQuery("form#newsletter-frm")[0].reset(); }, 2000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { jQuery('span#success-msg').html(''); for (i in json['error']) { var element = $('.newsletter-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">You have successfully subscribed to the newsletter</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |
Step 5: Create HTML file named
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<?php include('templates/header.php'); ?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Build a Newsletter Email Subscription with PHP and MySQL</h2> </div> <div class="row"> <div class="col-sm-12"><span id="success-msg"></span></div> </div> <form id="newsletter-frm" class="newsletter-frm"> <input type="hidden" name="action" value="create"> <div class="row align-items-center"> <div class="col-sm-6 offset-md-3"> <div> <h2 style="text-align: center;" class="text-muted">SUBSCRIBE NOW</h2> </div> <div class="form-group"> <div class="col-sm-12"> <input type="text" class="form-control newsletter-name" id="newsletter-name" placeholder="Name*" name="name"> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="text" class="form-control newsletter-email" id="newsletter-email" placeholder="Email*" name="email" > </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-12"> <button type="button" class="btn btn-info float-right" id="subscribe-newsletter">Subscribe</button> </div> </div> </div> </div> </form> </div> </section> <?php include('templates/footer.php');?> <script type="text/javascript"> jQuery(document).on('click', 'button#subscribe-newsletter', function() { jQuery.ajax({ type:'POST', url:'action.php', data:jQuery("form#newsletter-frm").serialize(), dataType:'json', beforeSend: function () { jQuery('button#subscribe-newsletter').button('Loding..'); }, complete: function () { jQuery('button#subscribe-newsletter').button('reset'); setTimeout(function () { jQuery("form#newsletter-frm")[0].reset(); }, 2000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { jQuery('span#success-msg').html(''); for (i in json['error']) { var element = $('.newsletter-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">You have successfully subscribed to the newsletter</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Build a Newsletter Email Subscription with PHP and MySQL | Tech Arise</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </body> </html> |