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

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

mysql> DESC subscribers; +-------+--------------+------+-----+---------+----------------+ | Field | Type         | Null | Key | Default | Extra          | +-------+--------------+------+-----+---------+----------------+ | id    | int(11)      | NO   | PRI | NULL    | auto_increment | | email | varchar(150) | NO   | UNI |         |                | +-------+--------------+------+-----+---------+----------------+ 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 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 19.1 shows the code for manage.php, which uses a few user-defined functions to eliminate repetitious code and so that you start thinking about creating functions on your own. The code looks long, but a line-by-line description follows, and the majority of the code is an HTML form, so no worries!

Listing 19.1. Subscribe and Unsubscribe with manage.php

 1:   <?php 2:   //set up a couple of functions 3:   function doDB() { 4:       global $mysqli; 5: 6:       //connect to server and select database; you may need it 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: 17: function emailChecker($email) { 18:     global $mysqli, $check_res; 19: 20:     //check that email is not already in list 21:     $check_sql = "SELECT id FROM SUBSCRIBERS 22:        WHERE email = '".$email."'"; 23:     $check_res = mysqli_query($mysqli, $check_sql) 24:        or die(mysqli_error($mysqli)); 25: } 26: 27: //determine if they need to see the form or not 28: if (!$_POST) { 29:     //they need to see the form, so create form block 30:     $display_block = " 31:     <form method=\"POST\" action=\"".$_SERVER["PHP_SELF"]."\"> 32: 33:     <p><strong>Your E-Mail Address:</strong><br/> 34:     <input type=\"text\" name=\"email\" size=\"40\"> 35: 36:     <p><strong>Action:</strong><br/> 37:     <input type=\"radio\" name=\"action\" 38:         value=\"sub\" checked> subscribe 39:     <input type=\"radio\" name=\"action\" 40:         value=\"unsub\"> unsubscribe 41: 42:     <p><input type=\"submit\" name=\"submit\" 43:        value=\"Submit Form\"></p> 44:     </form>"; 45: 46: } else if (($_POST) && ($_POST["action"] == "sub")) { 47:     //trying to subscribe; validate email address 48:     if ($_POST["email"] == "") { 49:         header("Location: manage.php"); 50:         exit; 51:     } else { 52:         //connect to database 53:         doDB(); 54: 55:         //check that email is in list 56:         emailChecker($_POST["email"]); 57: 58:         //get number of results and do action 59:         if (mysqli_num_rows($check_res) < 1) { 60:             //free result 61:             mysqli_free_result($check_res); 62: 63:             //add record 64:                $add_sql = "INSERT INTO subscribers (email) 65:                        VALUES('".$_POST["email"]."')"; 66:                $add_res = mysqli_query($mysqli, $add_sql) 67:                       or die(mysqli_error($mysqli)); 68:                  $display_block = "<p>Thanks for signing up!</p>"; 69: 70:              //close connection to MySQL 71:              mysqli_close($mysqli); 72:          } else { 73:              //print failure message 74:                    $display_block = "<p>You're already subscribed!</p>"; 75:          } 76:      } 77:  } else if (($_POST) && ($_POST["action"] == "unsub")) { 78:      //trying to unsubscribe; validate email address 79:      if ($_POST["email"] == "") { 80:          header("Location: manage.php"); 81:          exit; 82:      } else { 83:          //connect to database 84:          doDB(); 85: 86:          //check that email is in list 87:          emailChecker($_POST["email"]); 88: 89:          //get number of results and do action 90:          if (mysqli_num_rows($check_res) < 1) { 91:              //free result 92:              mysqli_free_result($check_res); 93: 94:              //print failure message 95:                 $display_block = "<p>Couldn't find your address!</p> 96:              <p>No action was taken.</p>"; 97:          } else { 98:              //get value of ID from result 99:              while ($row = mysqli_fetch_array($check_res)) { 100:                  $id = $row["id"]; 101:              } 102: 103:              //unsubscribe the address 104:              $del_sql = "DELETE FROM subscribers 105:                         WHERE id = '".$id."'"; 106:              $del_res = mysqli_query($mysqli, $del_sql) 107:                         or die(mysqli_error($mysqli)); 108:              $display_block = "<P>You're unsubscribed!</p>"; 109:          } 110:          mysqli_close($mysqli); 111:      } 112:  } 113:  ?> 114: <html> 115: <head> 116: <title>Subscribe/Unsubscribe to a Mailing List</title> 117: </head> 118: <body> 119: <h1>Subscribe/Unsubscribe to a Mailing List</h1> 120: <?php echo "$display_block"; ?> 121: </body> 122: </html>

Listing 19.1 may be long, but it's not complicated. In fact, it could be longer, were it not for the user-defined functions at the top of the script. One of the reasons for creating your own functions is to be able to reuse them within your scripts. Lines 315 set up the first function, doDB(), which is simply the database connection function. If the connection cannot be made, the script will exit when this function is called; otherwise, it will make the value of $mysqli available to other parts of your script. Lines 1725 define a function called emailChecker(), which takes an input and returns an outputlike most functions do. We'll look at this one in the context of the script, as we get to it.

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

Lines 3044 create the subscribe/unsubscribe form, using $_SERVER["PHP_SELF"] as the action (line 31), creating a text field called email for the user's email address and setting up a set of radio buttons (lines 3640) to find the desired task. At this point, the script breaks out of the if...else construct, skips down to line 114, and proceeds to print the HTML, which is stored in the variable called $display_block. The form is displayed 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, we need to do something. There are two possibilities: the subscribing and unsubscribing actions for the email address provided in the form. We determine which action to take by looking at the value of $_POST["action"] from the radio button group.

In line 46, if the presence of $_POST is true and the value of $_POST["action"] is "sub", we know the user is trying to subscribe. To subscribe, the user needs an email address, so we check for one in lines 4850. If no address is present, the user is redirected back to the form.

However, if an address is present, we call the doDB() function in line 53 to connect to the database so that we can issue queries. In line 56, we call the second of our user-defined functions: emailChecker(). This function takes an input ($_POST["email"], in this case) and processes it. If we look back to lines 2124, we 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.

By the Way

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 59 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, and the response is stored in lines 6468, and the failure message (if the address is already in the table) is stored in line 74. At that point, the script breaks out of the if...else construct, skips down to line 114, and proceeds to print the HTML. 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 we check for one in lines 7981. If no address is present, the user is sent back to the form.

If an address is present, we call the doDB() function in line 84 to connect to the database. Then, in line 87, we call emailChecker(), which again will return the resultset, $check_res. The number of records in the resultset is counted in line 90, 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 9596. 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 104108. At that point, the script breaks out of the if...else construct, skips down to line 114, 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. Successful subscription.


Figure 19.3. Subscription failure.


Figure 19.4. Successful unsubscribe action.


Figure 19.5. Unsuccessful unsubscribe action.


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




Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net