Build Newsletter System with PHP, MySQL & jQuery
Newsletter or Email Subscription is a commonly used functionality in the web applications. It is used in web application to allow users to subscribe with their email and get the updates daily, weekly, and monthly via email.
So, In this tutorial we will show you how to Build Newsletter System with PHP, MySQL, and jQuery. You can use this example to develop more features as per your requirement. You can also download the source code of the live example.
So let’s implement Newsletter System with PHP, Ajax & MySQL. look files structure:
- build-newsletter-system-with-php-mysql-and-jquery
- assets
- dist
- css
- style.css
- js
- custom.js
- templates
- header.php
- footer.php
- index.php
- newsletter.php
- verify_newsletter.php
- assets
Step 1: Create the database and Table
Run the following script against MySQL to create the database
newsletter
table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
CREATE TABLE `newsletter` ( `id` int(11) NOT NULL, `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 DEFAULT current_timestamp(), `modified` datetime NOT NULL DEFAULT current_timestamp(), `status` tinyint(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; COMMIT; |
Step 2: Create a class file named DbConnection.php (Database Configuration) inside “class/” folder
The
DbConnection.php
file is used to connect 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 |
<?php session_start(); /** * @package DBConnection class * * @author CodersMag Team * * @email info@codersmag.com * */ // Database Connection class DBConnection{ private $_hostName = 'localhost'; private $_userName = 'root'; private $_password = ""; private $_dbName = "demo_db"; public function getConnection(){ $mysqli = new mysqli($this->_hostName, $this->_userName, $this->_password, $this->_dbName); if($mysqli->connect_error){ die("Error failed to connect to MySQL: " . $mysqli->connect_error); } else { return $mysqli; } } } ?> |
Step 3: Create a class file named Newsletter.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 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 |
<?php /** * @package Newsletter class * * @author CodersMag Team * * @email info@codersmag.com * */ class Newsletter { private $NewsletterTable = 'newsletter'; private $mysqli; public function __construct($_db){ $this->mysqli = $_db; } // create record in database public function insert(){ if($this->name && $this->email && $this->verify_token) { $stmt = $this->mysqli->prepare(" INSERT INTO ".$this->NewsletterTable."(`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; } } } // update record in database public function update(){ if($this->verify_token) { $stmt = $this->mysqli->prepare(" UPDATE ".$this->NewsletterTable." 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; } } } // get user public function getUser() { if($this->email) { $stmtSubscriber = $this->mysqli->prepare("SELECT * FROM ".$this->NewsletterTable." WHERE email = '".$this->email."'"); $stmtSubscriber->execute(); $allResult = $stmtSubscriber->get_result(); $susbscriberRows = $allResult->num_rows; return $susbscriberRows; } } // token verification public function verifyToken() { if($this->verify_token) { $stmtSubscriber = $this->mysqli->prepare("SELECT * FROM ".$this->NewsletterTable." WHERE verify_token = '".$this->verify_token."'"); $stmtSubscriber->execute(); $allResult = $stmtSubscriber->get_result(); $susbscriberRows = $allResult->num_rows; return $susbscriberRows; } } } ?> |
Step 4: Create action file named newsletter.php
Manage ajax request and return as JSON data
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 |
<?php // include database class include_once 'class/DBConnection.php'; include_once 'class/Newsletter.php'; $_database = new DBConnection(); $_db = $_database->getConnection(); $_newsletter = new Newsletter($_db); // define array $json = array(); $errorMsg = ''; $json = array( 'status' => 'error', 'msg' => 'Something went wrong, please submit valid info.' ); if(empty($_POST['name'])){ $json['error']['name'] = 'Please enter your full name.'; } if(empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ $json['error']['email'] = 'Please enter your valid email address.'; } if(empty($json['error'])){ $name = $_POST['name']; $email = $_POST['email']; // generate verification token $verifyToken = md5(uniqid(mt_rand())); $_newsletter->email = $email; if($_newsletter->getUser()){ $json['msg'] = 'Your email already exists in our database.'; } else { $_newsletter->name = $name; $_newsletter->verify_token = $verifyToken; $result = $_newsletter->insert(); if($result){ $siteName = 'Coders Mag'; $siteEmail = 'contact@codersmag.com'; $siteURL = "https://codersmag.com/demos/php/build-newsletter-system-with-php-mysql-and-jquery/"; $verifyLink = $siteURL.'verify_newsletter.php?email_verify='.$verifyToken; $subject = 'Confirm Newsletter 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 verify 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">Verify Email</a> </p> <br><p><strong>Team '.$siteName.'</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){ $data = array( 'status' => 'ok', 'msg' => 'Verification link has been sent to your email address, please verify your email address.' ); } } } } else { $json['msg'] = $errorMsg; } header('Content-Type: application/json'); echo json_encode($json); ?> |
Step 5: Create action file named verify_newsletter.php
Manage email verification process
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 |
<?php // include database class include_once 'class/DBConnection.php'; include_once 'class/Newsletter.php'; $_database = new Database(); $_db = $_database->getConnection(); $_newsletter = new Newsletter($db); $statusMsg = ''; if(!empty($_GET['email_verify'])){ $verifyToken = $_GET['email_verify']; $_newsletter->verify_token = $verifyToken; if($_newsletter->verifyToken()){ $_newsletter->is_verified = 1; if($_newsletter->update()) { $statusMsg = '<p class="success">Your email 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>'; } } ?> <?php include('templates/header.php');?> <div class="content"> <div class="container-fluid"> <h2>Example: Build Newsletter System with PHP, MySQL and jQuery</h2> <div class="row"> <div class="col-lg-12"> <?php echo $statusMsg; ?> </div> </div> </div> </div> <?php include('templates/footer.php');?> |
Step 6: Create 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 |
<?php include('templates/header.php'); ?> <div class="content"> <div class="container-fluid"> <h2>Example: Build Newsletter System with PHP, MySQL and jQuery</h2> <div class="row"> <div class="col-lg-12"> <div class="main-content"> <div class="susbcribe-container"> <div class="top"> <span id="success-message"></span> <h2>Subscribe Now</h2> <h3>Subscribe for our <span>Latest</span> updates</h3> </div> <div class="bottom"> <form id="newsletter-form" class="newsletter-form" method="POST"> <div class="form-group"> <div class="col-sm-12"> <input type="text" class="form-control newsletter-name" id="name" placeholder="Full Name*" required=""> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="email" class="form-control newsletter-email" id="email" placeholder="Email Address*" required=""> </div> </div> <input type="button" id="subscribe-now" value="Subscribe Now"> </form> </div> </div> </div> </div> </div> </div> </div> <?php include('templates/footer.php');?> |
Step 7: Create JavaScript file
The following JavaScript code handles the request using jQuery and Ajax
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 |
/* *** Author: CodersMag Team Author URI: http://codersmag.com File Name : custom.js *** */ jQuery(document).on('click', 'input#subscribe-now', function() { var name = jQuery("#newsletter-form").find('.newsletter-name').val(); var email = jQuery("#newsletter-form").find('.newsletter-email').val(); jQuery.ajax({ type:'POST', url:'newsletter.php', data:{name:name,email:email}, dataType:'json', // beforeSend beforeSend: function () { jQuery('input#subscribe-now').button('Loding..'); }, //complete complete: function () { jQuery('input#subscribe-now').button('reset'); setTimeout(function () { jQuery("form#newsletter-form")[0].reset(); }, 2000); }, // success success: function (json) { $('.text-danger').remove(); if (json['error']) { jQuery('span#success-message').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-message').html('<div style="font-size: 14px;" class="alert alert-success d-flex align-items-center" role="alert">You have successfully subscribed to the newsletter</div>'); } }, // error message error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |
Step 8: Create header (header.php)
This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section.
Located at the top of a website, the header typically contains elements that include a company’s logo, website navigation, and contact information.
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 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Team TechArise"> <meta name="generator" content="TechArise 0.84.0"> <title>Build Newsletter System with PHP, MySQL and jQuery | Coders Mag</title> <link rel="canonical" href="https://techarise.com"> <link rel="icon" type="image/ico" href="https://codersmag.com/wp-content/themes/v1/favicon.ico"> <!-- Bootstrap core CSS --> <link href="assets/dist/css/bootstrap.min.css" rel="stylesheet"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> </head> <body> <div class="container py-3"> <header> <div class="d-flex flex-column flex-md-row align-items-center pb-3 mb-4 border-bottom"> <a href="https//techarise.com" class="d-flex align-items-center text-dark text-decoration-none"> <span class="fs-4">Coders Mag</span> </a> <nav class="d-inline-flex mt-2 mt-md-0 ms-md-auto"> <a class="me-3 py-2 text-dark text-decoration-none" href="https://codersmag.com">Home</a> <a class="me-3 py-2 text-dark text-decoration-none" href="https://codersmag.com/php-script-demos">Live Demos</a> </nav> </div> </header> |
Step 9: Create a view file named footer.php
This view contains the footer section of the webpage.
- jQuery – needed by Bootstrap JavaScript.
- Bootstrap JavaScript – to make cool UI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<footer class="pt-4 my-md-5 pt-md-5 border-top"> <div class="row"> <div class="col-12 col-md"> <small class="d-block mb-3 text-muted"> Copyright © 2011 - <?php print date('Y', time());?> <a href="https://codersmag.com" title="codersmag.com">CODERSMAG.COM</a> All rights reserved.</small> </div> </div> </footer> </div> <script src="assets/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="assets/js/custom.js"></script> </body> </html> |