Skip to main content

Managing a Simple Mailing List

This hour provides the first of several hands-on, small projects designed to pull together your PHP and MySQL knowledge. In this hour, you'll learn the methods for creating a managed distribution list, which can be used to send out newsletters or anything else that you want to send, to a list of email addresses in a database.
The mailing mechanism you'll use in this hour is not meant to be a replacement for mailing list software, which is specifically designed for bulk messages. The type of system you'll build in this lesson should be used for only small lists of fewer than a few hundred email addresses.
In this hour, you will learn how to
  • Create a subscribe/unsubscribe form and script
  • Create a front end for sending your message
  • Create the script that sends your message


    Developing the Subscription Mechanism

    You learned in earlier lessons that planning is the most important aspect of creating any product. In this case, think of the elements you will need for your subscription mechanism:
  • A table to hold email addresses
  • A way for users to add or remove their email addresses
  • A form and script for sending the message
The following sections will describe each item individually.

Creating the subscribers Table

You really need only one field in the subscribers table: to hold the email address of the user. However, you should have an ID field just for consistency among your tables, and also because referencing an ID is a lot simpler than referencing a long email address in where clauses. So, in this case, your MySQL query would look something like

mysql> create table subscribers (
    -> id int not null primary key auto_increment,
    -> email varchar (150) unique not null
    -> );
Query OK, 0 rows affected (0.00 sec)

Note the use of unique in the field definition for email. This means that although id is the primary key, duplicates should not be allowed in the email field either. The email field is a unique key, and id is the primary key.
This relationship is represented in the table information as MUL (or "multiple") in the Key field:

mysql> describe subscribers;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      |      | PRI | NULL    | auto_increment |
| email | varchar(150) | YES  | MUL | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec) 
 
Now that you have a table, you can create the form and 
script that place values in there.

Creating the Subscription Form

The subscription form will actually be an all-in-one form and script called manage.php, which will handle both subscribe and unsubscribe requests. Listing 18.1 shows the code for manage.php, which uses a few user-defined functions to eliminate repetitious code.
Listing 18.1 Subscribe and Unsubscribe with manage.php
  1: <?php
  2: //set up a couple of functions
  3: function doDB() {
  4:     global $conn;
  5:    //connect to server and select database; you may need it
  6:    $conn = mysql_connect("localhost", "joeuser", "somepass")
  7:         or die(mysql_error());
  8:    mysql_select_db("testDB",$conn) or die(mysql_error());
  9: }
 10: 
 11: function emailChecker($email) {
 12:     global $conn, $check_result;
 13:    //check that email is not already in list
 14:    $check = "select id from subscribers where email = '$email'";
 15:    $check_result = mysql_query($check,$conn) or die(mysql_error());
 16: }
 17: 
 18: //determine if they need to see the form or not
 19: if ($_POST[op] != "ds") {
 20:    //they do, so create form block
 21:    $display_block = "
 22:    <form method=POST action=\"$_SERVER[PHP_SELF]\">
 23: 
 24:    <p><strong>Your E-Mail Address:</strong><br>
 25:    <input type=text name=\"email\" size=40 maxlength=150>
 26: 
 27:    <p><strong>Action:</strong><br>
 28:    <input type=radio name=\"action\" value=\"sub\" checked> subscribe
 29:    <input type=radio name=\"action\" value=\"unsub\"> unsubscribe
 30: 
 31:    <input type=\"hidden\" name=\"op\" value=\"ds\">
 32: 
 33:    <p><input type=submit name=\"submit\" value=\"Submit Form\"></p>
 34:    </form>";
 35: 
 36: } else if (($_POST[op] == "ds") && ($_POST[action] == "sub")) {
 37:    //trying to subscribe; validate email address
 38:    if ($_POST[email] == "") {
 39:        header("Location: manage.php");
 40:        exit;
 41:    }
 42:    //connect to database
 43:    doDB();
 44:    //check that email is in list
 45:    emailChecker($_POST[email]);
 46: 
 47:    //get number of results and do action
 48:    if (mysql_num_rows($check_result) < 1) {
 49:        //add record
 50:        $sql = "insert into subscribers values('', '$_POST[email]')";
 51:        $result = mysql_query($sql,$conn) or die(mysql_error());
 52:        $display_block = "<P>Thanks for signing up!</P>";
 53:    } else {
 54:        //print failure message
 55:        $display_block = "<P>You're already subscribed!</P>";
 56:    }
 57: } else if (($_POST[op] == "ds") && ($_POST[action] == "unsub")) {
 58:    //trying to unsubscribe; validate email address
 59:    if ($_POST[email] == "") {
 60:    header("Location: manage.php");
 61:        exit;
 62:    }
 63:    //connect to database
 64:    doDB();
 65:    //check that email is in list
 66:    emailChecker($_POST[email]);
 67: 
 68:    //get number of results and do action
 69:    if (mysql_num_rows($check_result) < 1) {
 70:        //print failure message
 71:        $display_block = "<P>Couldn't find your address!</P>
 72:        <P>No action was taken.</P>";
 73:    } else {
 74:        //unsubscribe the address
 75:        $id = mysql_result($check_result, 0, "id");
 76:        $sql = "delete from subscribers where id = '$id'";
 77:        $result = mysql_query($sql,$conn) or die(mysql_error());
 78:        $display_block = "<P>You're unsubscribed!</p>";
 79:    }
 80: }
 81: ?>
 82: <html>
 83: <head>
 84: <title>Subscribe/Unsubscribe</title>
 85: </head>
 86: <body>
 87: <h1>Subscribe/Unsubscribe</h1>
 88: <?php echo "$display_block"; ?>
 89: </body>
 90: </html> 
 
 
 

Comments

Popular posts from this blog

How to make a Calculator

Calculator  - Visual Basic 2008 / 2010 Part- 1 This tutorial will show you how to make a basic calculator: Click on Project next to Create:  Click on Windows Form Application, and name the project "Your name's Calculator" and then click Ok. You can change the form text to "your name's calculator". Click on the form and then go to properties window, then change the text property. You also need to disable the maximize control of the form. That's because you don't want the user to maximize the calculator. Go to the properties window, and change the maximize box property to False:   You also need to change the FormBorderStyle property to Fixed3D   Add a button to the form and place on top of the form:   You might be surprised of this button because we should have placed a text box instead. Well, this is the cool thing about Visual Basic 2008, you can use a button to display text and results. Now we have to change the button prope

Professional WordPress Design and Development, 3rd Edition

Professional WordPress: Design and Development, 3rd Edition Brad Williams, David Damstra, Hal Stern ISBN: 978-1-118-98724-7 504 pages December 2014 Professional WordPress is the only WordPress book targeted to developers, with advanced content that exploits the full functionality of the most popular CMS in the world. Fully updated to align with WordPress 4.1, this edition has updated examples with all new screenshots, and full exploration of additional tasks made possible by the latest tools and features. You will gain insight into real projects that currently use WordPress as an application framework, as well as the basic usage and functionality of the system from a developer's perspective. The book's key features include detailed information and real-world examples that illustrate the concepts and techniques at work, plus code downloads and examples accessible through the companion website. Written by practicing WordPress developers, the c

SEO (Search Engine Optimization)

What is SEO? SEO is the active practice of optimizing a web site by improving internal and external aspects in order to increase the traffic the site receives from search engines. Firms that practice SEO can vary; some havea highly specialized focus while others take a more broad and general approach. Optimizing a web site for search engines can require looking at so many unique elements that many practitioners of SEO (SEOs) consider themselves to be in the broad field of website optimization (since so many of those elements intertwine). This guide is designed to describe all areas of SEO - from discovery of the terms and phrases that will generate traffic, to making a site search engine friendly to building the links and marketing the unique value of the site/organization's offerings. Why can't the search engines figure out my site without SEO help? Search engines are always working towards improving their technology to crawl the web more deeply and return increa