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> 

Listing 18.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 that you know you will be reusing a bit of code and don't want to continually retype it. Lines 3 9 set up the first function, doDB(), which is simply the database connection you've been making in your lessons for a while now. Lines 11 16 define a function called emailChecker(), which takes an input and returns an output like most functions do. We'll look at this one in the context of the script, as we get to it.

Line 19 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 value of $_POST[op] is not "ds", we know the user has not submitted the form; therefore, we must show it to the user. Lines 21 34 create the subscribe/unsubscribe form, using $_SERVER[PHP_SELF] as the action (line 22), creating a text field called email for the user's email address, and setting up a set of radio buttons (lines 28 29) to find the desired task. At this point, the script breaks out of the if...else construct, skips down to line 82, and proceeds to print the HTML. The form is displayed as shown in Figure 18.1.

Figure 18.1. The subscribe/ unsubscribe form.

graphics/18fig01.gif

If the value of $_POST[op] is indeed "ds", however, we need to do something. We have two possibilities: subscribe and unsubscribe. We determine which action to take by looking at the value of $_POST[action] the radio button group.

In line 36, if $_POST[op] is "ds" and $_POST[action] is "sub", we know the user is trying to subscribe. To subscribe, he will need an email address, so we check for one in lines 38 41. 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 43 to connect to the database because we need to perform a query (or two). In line 45, we call the second of our user-defined functions, emailChecker(). This function takes an input ($_POST[email]) and processes it. If we look back to lines 12 15, we see that the function is checking for an id value in the subscribers table that matches the value of the input. The function then returns the resultset, $check_result, for use within the larger script.

graphics/book.gif

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


Jump down to line 48 to see how $check_result is used: The number of records in $check_result 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 50 52, and the failure message (if the address is already in the table) is stored in line 55. At that point, the script breaks out of the if...else construct, skips down to line 82, and proceeds to print the HTML. You'll test this functionality later.

The last combination of inputs occurs if the value of $_POST[op] is "ds" and $_POST[action] is "unsub". In this case, the user is trying to unsubscribe. To unsubscribe, he will need an email address, so we check for one in lines 59 61. 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 64 to connect to the database. Then, in line 66, we call emailChecker(), which again will return the resultset, $check_result. The number of records in the resultset is counted in line 69, 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 71 72. The user is unsubscribed(the record deleted) and the response is stored in lines 75 77, and the failure message (if the address is already in the table) is stored in line 78. At that point, the script breaks out of the if...else construct, skips down to line 82, and proceeds to print the HTML.

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

Figure 18.2. Successful subscription.

graphics/18fig02.gif

Figure 18.3. Subscription failure.

graphics/18fig03.gif

Figure 18.4. Successful unsubscribe action.

graphics/18fig04.gif

Figure 18.5. Unsuccessful unsubscribe action.

graphics/18fig05.gif

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



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

Similar book on Amazon

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