loading

How to Newsletter Email Subscription with PHP and MySQL

How to Newsletter Email Subscription with PHP and MySQL

How to Newsletter Email Subscription with PHP and MySQL

0 Sales

Free

A newsletter subscription is a popular feature on a website or blog. An email subscription allows the visitor to get updates through email. 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 newsletter updates from the website.

 

Updates from the website are delivered to the subscriber's email address when they sign up for a newsletter. PHP may be used to simply construct email subscription capabilities. In this article, we will teach you how to use PHP and MySQL to develop email subscription capabilities in a web site.

 

The following functionality will be included in the sample email subscription script.

 - Make an HTML subscription form.

 - Using PHP and MySQL, add subscription information to the database.

 - Send the verification link to yourself through email.

 - Verify the subscriber's email address.

Try taking a look at the file structure before beginning to construct email subscription feature using PHP.

 

email_subscription_with_php/
├── config.php
├── index.html
├── subscription.php
├── Subscriber.class.php
├── js/
│   └── jquery.min.js
└── css/
    └── style.css

 

Create Database Table

 

A table in the database is necessary to store subscriber information. The SQL below creates a table called subscribers in the MySQL database.

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; 

 

Subscriber Class

The Subscriber module allow us to connect with the database and performs the database related tasks using PHP and MySQL.

1. __construct() – Establish a connection to the MySQL database.

2. getRows() – Retrieve the database records.

3. insert() – Creates a new entry in the database.

4. update() – Updates a database record.

5. delete() — This function deletes records from the database.

 

<?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; 
    } 
}

 

Site Settings and Database Configuration (config.php)

 

This file defines the fundamental site settings and database setup variables.

 - $siteName – The site's name.

 - $siteEmail – The sender's email address.

 - DB HOST is the database host.

 - DB USERNAME – The database's username.DB PASSWORD — Database password.

 - DB NAME – The database's name.

<?php 
/* 
 * Basic Site Settings and Database Configuration 
 */ 
 
// Site Settings 
$siteName 'Demo Site'; 
$siteEmail '[email protected]'; 
 
$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'); 

 

Email Subscription Form

Create an HTML form to collect 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>

 

Subscription Form Submission


The subscription form will be sent to the server-side script without requiring a page refresh.

Because Ajax is required to post form data, the jQuery library must be included first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

 

The form data is provided using jQuery and Ajax upon submission.

 - jQuery is used to verify the name and email inputs with Regex.

 - The data from the form is sent to the server-side script (subscription.php) through the $.ajax() function.

 - The status is displayed to the user based on the answer.

 

<script>
$(document).ready(function(){
    $('#subscribeBtn').on('click', function(){
        // Remove previous status message
        $('.status').html('');
		
        // Email and name regex
        var regEmail = /^[A-Z0-9._%+-][email protected]([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>

 

Insert Subscriber Info in Database (subscription.php)

 

If you receive an email subscription request (subscribe):

 - PHP's $_POST function is used to retrieve form data.

 - PHP also provides server-side validation for form input fields.

 - Using the Subscriber class's getRows() method, see if the specified email already exists.

 - Insert subscriber information into the database using the Subscriber class's insert() method.

 - 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); 
} 
?>

 

Email Verification (subscription.php)


If you receive an email verification request (email_verify):

 - Compare the verification code to the subscriber.

 - Update the verification status in the Subscriber class's database update() method.

 - The email verification status is 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&amp;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 
} 
?>

 

Conclusion

 

This email subscription script enables you to rapidly incorporate newsletter subscription features on your website. The email subscription and verification functions work without requiring a page refresh, making the mailing process more user-friendly. You may simply customise the functionality of this email subscription script to meet your own requirements.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 22, 2022

Updated Date : Jan 23, 2022

Ratings

Comments : 0

Downloads : 0