Home > Articles > Business & Management > Personal Development

Managing a Simple Mailing List in PHP and MySQL

📄 Contents

  1. Developing the Subscription Mechanism
  2. Developing the Mailing Mechanism
  3. Summary
  4. Q&A
  5. Workshop
This chapter provides the first of several hands-on, small projects designed to pull together your PHP and MySQL knowledge. In this chapter, you learn how to create a managed distribution list that you can use to send out newsletters or anything else to a list of email addresses in a database.
This chapter is from the book

The mailing mechanism you use in this chapter is not meant to be a replacement for mailing list software, which is specifically designed for bulk messages. You should use the type of system you build in this chapter only for small lists, fewer than a few hundred email addresses.

Developing the Subscription Mechanism

You learned in earlier chapters that planning is the most important aspect of creating any product. In this case, think of the elements you 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 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 because referencing an ID is much simpler than referencing a long email address in where clauses. So, in this case, your MySQL query would look something like this:

CREATE TABLE subscribers (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR (150) UNIQUE NOT NULL
);

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.

Log in to MySQL via the command line and issue this query. After creating the table, issue a DESC or DESCRIBE query to verify that the table has been created to your specifications, such as the following:

mysql> DESC subscribers;

+-------+--------------+------+-----+---------+----------------+

| Field | Type         | Null | Key | Default | Extra          |

+-------+--------------+------+-----+---------+----------------+

| id    | int(11)      | NO   | PRI | NULL    | auto_increment |

| email | varchar(150) | NO   | UNI | NULL    |                |

+-------+--------------+------+-----+---------+----------------+

2 rows in set (0.00 sec)

Now that you have a table in your database, you can create the form and script that place values in there.

Creating an Include File for Common Functions

Although there are only two scripts in this process, some common functions exist between them—namely, the database connection information. To make your scripts more concise in situations like this, take the common functions or code snippets and put them in a file to be included in your other scripts via the include() function that you learned about in Chapter 13, “Working with Files and Directories.” Listing 19.1 contains the code shared by the scripts in this chapter.

Listing 19.1 Common Functions in an Included File

1:  <?php
2:  // function to connect to database
3:  function doDB() {
4:      global $mysqli;
5:
6:      //connect to server and select database
7:      $mysqli = mysqli_connect("localhost", "joeuser",
8:          "somepass", "testDB");
9:
10:      //if connection fails, stop script execution
11:      if (mysqli_connect_errno()) {
12:          printf("Connect failed: %s\n", mysqli_connect_error());
13:          exit();
14:      }
15:  }
16:  // function to check email address
17:  function emailChecker($email) {
18:     global $mysqli, $safe_email, $check_res;
19:
20:     //check that email is not already in list
21:     $safe_email = mysqli_real_escape_string($mysqli, $email);
22:     $check_sql = "SELECT id FROM SUBSCRIBERS
23:          WHERE email = '".$safe_email."'";
24:     $check_res = mysqli_query($mysqli, $check_sql)
25:          or die(mysqli_error($mysqli));
26:  }
27:  ?>

Lines 3–15 set up the first function, doDB(), which is simply the database connection function. If the connection cannot be made, the script exits when this function is called; otherwise, it makes the value of $mysqli available to other parts of your script.

Lines 17–26 define a function called emailChecker(), which takes an input and returns an output—like most functions do. We look at this one in the context of the script, as we get to it in Listing 19.2

Save this file as ch19_include.php and place it on your web server. In Listing 19.2, you will see how to include this file when necessary in your scripts.

Creating the Subscription Form

The subscription form is actually an all-in-one form and script called manage.php, which handles both subscribe and unsubscribe requests. Listing 19.2 shows the code for manage.php, which uses a few user-defined functions to eliminate repetitious code and to start you thinking about creating functions on your own. The code looks long, but a line-by-line description follows (and a lot of the code just displays an HTML form, so no worries).

Listing 19.2 Subscribe and Unsubscribe with manage.php

1:  <?php
2:  include 'ch19_include.php';
3:  //determine if they need to see the form or not
4:  if (!$_POST) {
5:      //they need to see the form, so create form block
6:     $display_block = <<<END_OF_BLOCK
7:     <form method="POST" action="$_SERVER[PHP_SELF]">
8:
9:     <p><label for="email">Your E-Mail Address:</label><br/>
10:    <input type="email" id="email" name="email"
11:           size="40" maxlength="150" /></p>
12:
13:    <fieldset>
14:    <legend>Action:</legend><br/>
15:    <input type="radio" id="action_sub" name="action"
16:           value="sub" checked />
17:    <label for="action_sub">subscribe</label><br/>
18:    <input type="radio" id="action_unsub" name="action"
19:           value="unsub" />
20:    <label for="action_unsub">unsubscribe</label>
21:    </fieldset>
22:
23:    <button type="submit" name="submit" value="submit">Submit</button>
24:    </form>
25:  END_OF_BLOCK;
26:  } else if (($_POST) && ($_POST['action'] == "sub")) {
27:      //trying to subscribe; validate email address
28:      if ($_POST['email'] == "") {
29:          header("Location: manage.php");
30:          exit;
31:      } else {
32:          //connect to database
33:          doDB();
34:
35:          //check that email is in list
36:          emailChecker($_POST['email']);
37:
38:          //get number of results and do action
39:          if (mysqli_num_rows($check_res) < 1) {
40:              //free result
41:              mysqli_free_result($check_res);
42:
43:              //add record
44:              $add_sql = "INSERT INTO subscribers (email)
45:                         VALUES('".$safe_email."')";
46:              $add_res = mysqli_query($mysqli, $add_sql)
47:                         or die(mysqli_error($mysqli));
48:              $display_block = "<p>Thanks for signing up!</p>";
49:
50:              //close connection to MySQL
51:              mysqli_close($mysqli);
52:          } else {
53:              //print failure message
54:              $display_block = "<p>You're already subscribed!</p>";
55:          }
56:      }
57:  } else if (($_POST) && ($_POST['action'] == "unsub")) {
58:      //trying to unsubscribe; validate email address
59:      if ($_POST['email'] == "") {
60:          header("Location: manage.php");
61:          exit;
62:      } else {
63:          //connect to database
64:          doDB();
65:
66:          //check that email is in list
67:          emailChecker($_POST['email']);
68:
69:          //get number of results and do action
70:          if (mysqli_num_rows($check_res) < 1) {
71:              //free result
72:              mysqli_free_result($check_res);
73:
74:              //print failure message
75:              $display_block = "<p>Couldn't find your address!</p>
76:              <p>No action was taken.</p>";
77:          } else {
78:              //get value of ID from result
79:              while ($row = mysqli_fetch_array($check_res)) {
80:                  $id = $row['id'];
81:              }
82:
83:              //unsubscribe the address
84:              $del_sql = "DELETE FROM subscribers
85:                          WHERE id = ".$id;
86:              $del_res = mysqli_query($mysqli, $del_sql)
87:                         or die(mysqli_error($mysqli));
88:              $display_block = "<p>You're unsubscribed!</p>";
89:          }
90:          mysqli_close($mysqli);
91:      }
92:  }
93:  ?>
94:  <!DOCTYPE html>
95:  <html>
96:  <head>
97:  <title>Subscribe/Unsubscribe to a Mailing List</title>
98:  </head>
99:  <body>
100: <h1>Subscribe/Unsubscribe to a Mailing List</h1>
101: <?php echo "$display_block"; ?>
102: </body>
103: </html>

Listing 19.2 might be long, but it’s not complicated. In fact, it could be longer were it not for the user-defined functions placed in ch19_include.php and included on line 2 of this script.

Line 4 starts the main logic of the script. Because this script performs several actions, you need to determine which action it is currently attempting. If the presence of $_POST is false, you know that the user has not submitted the form; therefore, you must show the form to the user.

Lines 6–25 create the subscribe/unsubscribe form by storing a string in the $display_block variable using the heredoc format. In the heredoc format, the string delimiter can be any string identifier following <<<, as long as the ending identifier is on its own line, as you can see in this example on line 25.

In the form, we use $_SERVER[PHP_SELF] as the action (line 7), and then create a text field called email for the user’s email address (lines 9–11) and set up a set of radio buttons (lines 13–21) to find the desired task. At the end of the string creation, the script breaks out of the if...else construct, skips down to line 101, and proceeds to print the HTML stored in the $display_block variable. The form displays as shown in Figure 19.1.

Figure 19.1

Figure 19.1 The subscribe/unsubscribe form.

Back inside the if...else construct, if the presence of $_POST is true, you need to do something. There are two possibilities: the subscribing and unsubscribing actions for the email address provided in the form. You determine which action to take by looking at the value of $_POST['action'] from the radio button group.

In line 26, if the presence of $_POST is true and the value of $_POST['action'] is "sub", you know the user is trying to subscribe. To subscribe, the user needs an email address, so check for one in lines 28–30. If no address is present, redirect the user back to the form.

However, if an address is present, call the doDB() function (stored in ch19_include.php) in line 34 to connect to the database so that you can issue queries. In line 36, you call the second of our user-defined functions: emailChecker(). This function takes an input ($_POST['email'], in this case) and processes it. If you look back to lines 21–25 of Listing 19.1, you’ll see code within the emailChecker() function that issues a query in an attempt to find an id value in the subscribers table for the record containing the email address passed to the function. The function then returns the resultset, called $check_res, for use within the larger script.

Jump down to line 39 of Listing 19.2 to see how the $check_res variable is used: The number of records referred to by the $check_res variable is counted to determine whether the email address already exists in the table. If the number of rows is less than 1, the address is not in the list, and it can be added. The record is added, the response is stored in lines 44–48, and the failure message (if the address is already in the table) is stored in line 54. At that point, the script breaks out of the if...else construct, skips down to line 101, and proceeds to print the HTML currently stored in $display_block. You’ll test this functionality later.

The last combination of inputs occurs if the presence of $_POST is true and the value of the $_POST['action'] variable is "unsub". In this case, the user is trying to unsubscribe. To unsubscribe, an existing email address is required, so check for one in lines 59–61. If no address is present, send the user back to the form.

If an address is present, call the doDB() function in line 64 to connect to the database. Then, in line 67, you call emailChecker(), which again returns the resultset, $check_res. Line 70 counts the number of records in the result set to determine whether the email address already exists in the table. If the number of rows is less than 1, the address is not in the list and it cannot be unsubscribed.

In this case, the response message is stored in lines 75–76. However, if the number of rows is not less than 1, the user is unsubscribed (the record deleted) and the response is stored in lines 84–88. At that point, the script breaks out of the if...else construct, skips down to line 101, and proceeds to print the HTML.

Figures 19.2 through 19.5 show the various results of the script, depending on the actions selected and the status of email addresses in the database.

Figure 19.2

Figure 19.2 Successful subscription.

Figure 19.3

Figure 19.3 Subscription failure.

Figure 19.4

Figure 19.4 Successful unsubscribe action.

Figure 19.5

Figure 19.5 Unsuccessful unsubscribe action.

Next, you create the form and script that sends along mail to each of your subscribers.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020