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
  • Print
  • + Share This
  • 💬 Discuss
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.

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 (

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;
6:      //connect to server and select database
7:      $mysqli = mysqli_connect("localhost", "joeuser",
8:          "somepass", "testDB");
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;
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]">
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>
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>
23:    <button type="submit" name="submit" value="submit">Submit</button>
24:    </form>
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();
35:          //check that email is in list
36:          emailChecker($_POST['email']);
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);
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>";
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();
66:          //check that email is in list
67:          emailChecker($_POST['email']);
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);
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:              }
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.

  • + Share This
  • 🔖 Save To Your Account


comments powered by Disqus