A newsletter subscription is a frequently used website or blog feature. The visitor can choose to get updates by email by signing up for an email subscription. The most significant aspect of email marketing is the email subscription feature. The majority of websites include an email subscription option, which allows site users to get daily or weekly updates from the website.
The website’s updates are sent to the subscriber’s email address when they sign up for a newsletter. PHP makes it simple to create email subscription capabilities. In this article, we’ll teach you how to use PHP and MySQL to develop email subscription capabilities in a web application.
The following functionality will be included in the example email subscription script.
Using HTML, create a subscription form.
Using PHP and MySQL, add subscription information to the database.
Send the verification link to your email address.
Verify the subscriber’s email address.
Take a look at the file structure before starting to construct email subscription feature with PHP.
email_subscription_with_php/ ├── config.php ├── index.html ├── subscription.php ├── Subscriber.class.php ├── js/ │ └── jquery.min.js └── css/ └── style.css
Make a database table.
A table in the database is required to store the subscriber information. In the MySQL database, the following SQL creates a subscribers table.
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_code` 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;
Class of Subscribers
The Subscriber class uses PHP and MySQL to connect to the database and handle database-related tasks.
Connect to the MySQL database via __construct().
getRows() — Retrieves the database’s records.
insert() — This method creates a new record in the database.
update() – Updates a database record.
Delete records from the database with delete().
<?php
/*
* Subscriber Class
* This class is used for database related (connect, fetch, insert, update, and delete) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class Subscriber {
private $dbHost = DB_HOST;
private $dbUsername = DB_USERNAME;
private $dbPassword = DB_PASSWORD;
private $dbName = DB_NAME;
private $userTbl = 'subscribers';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Returns rows from the database based on the conditions
* @param string name of the table
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->userTbl;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}else{
$sql .= ' ORDER BY id DESC ';
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$result = $this->db->query($sql);
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
$data = '';
}
}else{
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
return !empty($data)?$data:false;
}
/*
* Insert data into the database
* @param string name of the table
* @param array the data for inserting into the table
*/
public function insert($data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$this->db->real_escape_string($val)."'";
$i++;
}
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
return $insert?$this->db->insert_id:false;
}else{
return false;
}
}
/*
* Update data into the database
* @param string name of the table
* @param array the data for updating into the table
* @param array where condition on updating data
*/
public function update($data, $conditions){
if(!empty($data) && is_array($data)){
$colvalSet = '';
$whereSql = '';
$i = 0;
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
$i++;
}
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
return $update?$this->db->affected_rows:false;
}else{
return false;
}
}
/*
* Delete data from the database
* @param string name of the table
* @param array where condition on deleting data
*/
public function delete($conditions){
$whereSql = '';
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$query = "DELETE FROM ".$this->userTbl.$whereSql;
$delete = $this->db->query($query);
return $delete?true:false;
}
}
Configuration of the Site and the Database (config.php)
This file contains the fundamental site settings and database setup variables.
$siteName is the site’s name.
$siteEmail – The email address of the sender.
DB
_HOST is the database host.
DB USERNAME is the database username.
DB NAME – Database name _PASSWORD – Database password
<?php
/*
* Basic Site Settings and Database Configuration
*/
// Site Settings
$siteName = 'Demo Site';
$siteEmail = 'sender@codex.com';
$siteURL = ($_SERVER["HTTPS"] == "on")?'https://':'http://';
$siteURL = $siteURL.$_SERVER["SERVER_NAME"].dirname($_SERVER['REQUEST_URI']).'/';
// Database configuration
define('DB_HOST', 'MySQL_Database_Host');
define('DB_USERNAME', 'MySQL_Database_Username');
define('DB_PASSWORD', 'MySQL_Database_Password');
define('DB_NAME', 'MySQL_Database_Name');
Subscription Form for Email
Create an HTML form to receive visitor input (name and email).
<!-- Display form submission status -->
<div class="status"></div>
<!-- Subscription form -->
<form action="#" id="subsFrm" method="post">
<input type="text" id="name" placeholder="Full Name" required="">
<input type="email" id="email" placeholder="E-mail" required="">
<input type="button" id="subscribeBtn" value="Subscribe Now">
</form>
Submission of the Subscription Form
Without refreshing the page, the subscription form will be submitted to the server-side script.
Because the form data is submitted using Ajax, the jQuery library must be included first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
On submission, the form data is submitted using jQuery and Ajax.
The name and email inputs are validated with Regex using jQuery.
The form data is posted to the server-side script (subscription.php) via $.ajax() method.
Based on the response, the status is shown to the user.
<script>
$(document).ready(function(){
$('#subscribeBtn').on('click', function(){
// Remove previous status message
$('.status').html('');
// Email and name regex
var regEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
// Get input values
var name = $('#name').val();
var email = $('#email').val();
// Validate input fields
if(name.trim() == '' ){
alert('Please enter your name.');
$('#name').focus();
return false;
}else if (!regName.test(name)){
alert('Please enter a valid name (first & last name).');
$('#name').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#email').focus();
return false;
}else if(email.trim() != '' && !regEmail.test(email)){
alert('Please enter a valid email.');
$('#email').focus();
return false;
}else{
// Post subscription form via Ajax
$.ajax({
type:'POST',
url:'subscription.php',
dataType: "json",
data:{subscribe:1,name:name,email:email},
beforeSend: function () {
$('#subscribeBtn').attr("disabled", "disabled");
$('.content-frm').css('opacity', '.5');
},
success:function(data){
if(data.status == 'ok'){
$('#subsFrm')[0].reset();
$('.status').html('<p class="success">'+data.msg+'</p>');
}else{
$('.status').html('<p class="error">'+data.msg+'</p>');
}
$('#subscribeBtn').removeAttr("disabled");
$('.content-frm').css('opacity', '');
}
});
}
});
});
</script>
Subscriber information should be entered into the database (subscription.php)
If you receive an email subscription request (subscribe):
PHP’s $_POST function retrieves form data and performs server-side validation on form input fields.
Using the Subscriber class’s getRows() function, see if the specified email already exists.
Use the Subscriber class’s insert() function to store subscriber information in the database.
PHP is used to send a verification email.
Return the response in JSON format.
<?php
// Include config file
require_once 'config.php';
// Include Subscriber class
require_once 'Subscriber.class.php';
$subscriber = new Subscriber();
if(isset($_POST['subscribe'])){
$errorMsg = '';
// Default response
$response = array(
'status' => 'err',
'msg' => 'Something went wrong, please try after some time.'
);
// Input fields validation
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 validation successful
if(empty($errorMsg)){
$name = $_POST['name'];
$email = $_POST['email'];
$verify_code = md5(uniqid(mt_rand()));
// Check whether the given email already exists
$con = array(
'where' => array(
'email' => $email
),
'return_type' => 'count'
);
$prevRow = $subscriber->getRows($con);
if($prevRow > 0){
$response['msg'] = 'Your email already exists in our subscribers list.';
}else{
// Insert subscriber info
$data = array(
'name' => $name,
'email' => $email,
'verify_code' => $verify_code
);
$insert = $subscriber->insert($data);
if($insert){
// Verification email configuration
$verifyLink = $siteURL.'subscription.php?email_verify='.$verify_code;
$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.">";
// Send verification email
$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;
}
// Return response
echo json_encode($response);
}
?>
Verification of Email (subscription.php)
If you receive an email verification request (email verify):
Compare the verification code to verify the subscriber.
Update the verification status in the Subscriber class’s database update() function.
The email verification status will be displayed.
<?php
// Include config file
require_once 'config.php';
// Include Subscriber class
require_once 'Subscriber.class.php';
$subscriber = new Subscriber();
if(!empty($_GET['email_verify'])){
$verify_code = $_GET['email_verify'];
$con = array(
'where' => array(
'verify_code' => $verify_code
),
'return_type' => 'count'
);
$rowNum = $subscriber->getRows($con);
if($rowNum > 0){
$data = array(
'is_verified' => 1
);
$con = array(
'verify_code' => $verify_code
);
$update = $subscriber->update($data, $con);
if($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>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Email Verification by CodexWorld</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<!-- web-fonts -->
<link href="//fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i&subset=latin-ext" rel="stylesheet">
<!-- Stylesheet file -->
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body class="subs">
<div class="container">
<div class="subscribe box-sizing">
<div class="sloc-wrap box-sizing">
<div class="sloc-content">
<div class="sloc-text">
<div class="sloc-header"><?php echo $statusMsg; ?></div>
</div>
<a href="<?php echo $siteURL; ?>" class="cwlink">Go to Site</a>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
}
?>
Note :
This email subscription script makes it simple to add newsletter subscription capabilities to your website. The newsletter process is made easier by the fact that the email subscription and verification functions do not require a page refresh. This email subscription script’s functionality can simply be enhanced to suit your needs.