By Julie Meloni Published May 29, 2012 by Sams. Part of the Sams Teach Yourself series. Sample Chapter is provided courtesy of Sams Publishing.

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.

In this chapter, you learn the following:

  • How to create a subscribe/unsubscribe form and script
  • How to create a front end for sending your message
  • How to create the script that sends your message


As with all the small sample projects in this book, these projects might not be exactly what you plan to build with your new PHP and MySQL knowledge. However, I cannot stress enough that the concepts and examples shown in this and other projects are similar to those you will encounter when developing any application that uses CRUD functionality (create, read, update, delete).

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

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.

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

Figure 19.2 Successful subscription.

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 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.


You can learn more about the heredoc and other string formats in the PHP Manual at

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 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.


Note the definition of global variables at the beginning of both user-defined functions in Listing 19.1. These variables need to be shared with the entire script, and so are declared global.

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.4 Successful unsubscribe action.
Figure 19.5 Unsuccessful unsubscribe action.

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

Developing the Mailing Mechanism

With the subscription mechanism in place, you can create a basic form interface for a script that takes the content of your form and sends it to every address in your subscribers table. This is another one of those all-in-one scripts, called sendmymail.php, and it is shown in Listing 19.3.

Figure 19.3 Subscription failure.


Before attempting to use the script in this section, make sure that you have read the section in Chapter 11, “Working with Forms,” regarding the configuration in your php.ini file. The php.ini file is required to send mail.

As in Listing 19.2, the file of user-defined functions is included on line 2. Although only the database connection function is used in this file, there’s no harm in having the other function in the file, as well.

The main logic of the script starts at line 3, where you determine whether the user has seen the form yet. If the presence of the $_POST variable is false, you know the user has not submitted the form; therefore, you must show the form.

Lines 5-15 create the form for sending the newsletter to your subscriber list, which uses $_SERVER[PHP_SELF] as the action (line 6), creates a text field called subject for the subject of the mail, and creates a textarea called message for the body of the mail to be sent.

At this point, the script breaks out of the if...else construct, and the HTML is printed. The form displays as shown in Figure 19.6.

Figure 19.6 Form for sending the bulk mail.

If the presence of $_POST is not false, the script should send the form to the email addresses in the subscribers table. Before sending the message, you must check for the two required items from the form in lines 18-20: $_POST['subject'] and $_POST['message']. If either of these items is not present, redirect the user to the form again.

If the required items are present, the script moves on to line 24, which calls the database connection function. A query is issued in line 33, which grabs all the email addresses from the subscribers table. There is no order to these results, although you could throw an order by clause in there if you want to send them out in alphabetic order for whatever reason.

Lines 37-38 create a From: mail header, which is used inside the upcoming while loop, when the mail is sent. This header ensures that the mail looks like it is from a person and not a machine because you’ve specifically provided a value in this string. The while loop, which begins on line 40, extracts the email addresses from the resultset one at a time. On line 41, you use the set_time_limit() function to set the time limit to 0, or “no limit.” Doing so allows the script to run for as long as it needs to.


Because the script in Listing 19.3 simply executes the mail() function numerous times, it does not take into account the queuing factors in actual mailing list software, which are designed to ease the burden on your outgoing mail server. Using set_time_limit() does not ease its burden; it just allows the script to continue to run when it might have timed out before.

In lines 43-44, the mail is sent using the mail() function, inserting the values from the form where appropriate. Line 45 adds to a string that is later printed to the screen, which shows to whom the mail was sent. Figures 19.7 and 19.8 show the outcome of the script.

Figure 19.7 Mail has been sent!
Figure 19.8 The mail arrived safely.


In this chapter, you applied your basic PHP and MySQL knowledge to the creation of a personal mailing list. Included were the database table creation, the subscribe and unsubscribe mechanisms, and the form and script for sending the mail.


  • Q.How can I ease the burden on my mail server?
  • A. Besides looking into packaged mailing list software, you can bypass the mail() function and talk directly to your SMTP server via a socket connection. Such an example is shown in the PHP manual for the fsockopen() function (, as well as in other developer resource sites.
  • Q.Where do bounced messages go?
  • A. As with any email (not just those sent in the manner described in this chapter), bounces go to whatever address you specify in your From: or Reply-to: mail headers.


The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.


  1. Which PHP function sends mail?
  2. Why is $mysqli named as a global variable in Listing 19.1?
  3. What PHP function call causes the script to execute for as long as it needs to run?


  1. This is not a trick question. It’s the mail() function!
  2. Because the variable $mysqli is created and assigned a value in a function that is included in one script for use by another, the variable must be declared as global to ensure it is usable outside of the confines of the function in which it was created.
  3. set_time_limit(0)


  1. Modify the manage.php script to display the user’s email as part of the response message for any action that is taken.
  2. Modify the sendmymail.php script to add additional form fields that will correspond to section headings in the message string itself. Remember that when the form is submitted, those strings will have to be concatenated into one message string that is sent to the mail() function.© 2013 Pearson Education, Inc. All rights reserved.
  3. 800 East 96th Street Indianapolis, Indiana 46240