Tải bản đầy đủ (.pdf) (30 trang)

Beginning PHP6, Apache, MySQL Web Development- P18 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (486.75 KB, 30 trang )

Chapter 14: Mailing Lists
481
6. Click the link at the bottom of the page to send a message to your users. A new page appears
where you can compose a new message and send it either to a single mailing list or to the
users of all the mailing lists, as shown in Figure 14 - 2 . Since you just created these pages, you
don ’ t have any users yet. You can compose a message, but it won ’ t go to anyone. You need to
create the user pages, which you ’ ll do shortly.
Figure 14-2
How It Works
A common practice is to post a form back to itself, and you certainly could have done that here. In fact,
you have done this in earlier projects in this book. When your page contains data that needs to be
inserted into a database, however, you need to think twice about a self - posting form. If the user were
to refresh or reload the page, all of your database functions would run again, and that could be
disastrous. You could end up with duplicate data or delete records you didn ’ t mean to delete.
To minimize that probability, you post to a separate script called
ml_admin_transact.php . This page
handles all of the necessary database transactions, and then directs you back to the page from which
you came. No harm will come to your database if the user reloads the page at that point.
To accommodate having several forms post their information to a central transaction script, all of your
submit buttons have the same name, “ action, ” but each has a different value. The transaction script
can check the value of the
$_POST[ ‘ action ’ ] variable to see which button was pressed and perform
the appropriate actions.
c14.indd 481c14.indd 481 12/10/08 6:02:31 PM12/10/08 6:02:31 PM
482
Part II: Comic Book Fan Site
In ml_admin.php , you present a form that collects information to be sent to ml_admin_transact
.php
. The first portion of the form is used to create new mailing lists, and is basic HTML because it is
always visible.
< form method=”post” action=”ml_admin_transact.php” >


< p > < label for=”listname” > Add Mailing List: < /label > < br / >
< input type=”text” id=”listname” name=”listname” maxlength=”100” / >
< input type=”submit” name=”action” value=”Add New Mailing List” / >
< /p >

The second portion of the form allows you to delete a mailing list, and should only be shown if there
are mailing lists available to delete. You first query the database for a list of mailing lists, and if

mysql_num_rows() returns a value larger than 0, you display a select element populated with the
lists. Each
option displays the list ’ s name and uses the list ’ s ID as its value.
< ?php
$query = ‘SELECT
ml_id, listname
FROM
ml_lists
ORDER BY
listname ASC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

if (mysql_num_rows($result) > 0) {
echo ‘ < p > < label for=”ml_id” > Delete Mailing List: < /label > < br / > ’;
echo ‘ < select name=”ml_id” id=”ml_id” > ’;
while ($row = mysql_fetch_array($result)) {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” > ’ . $row[‘listname’] .
‘ < /option > ’;
}
echo ‘ < /select > ’;
echo ‘ < input type=”submit” name=”action” value=”Delete ‘ .
‘Mailing List” / > ’;

echo ‘ < /p > ’;
}
mysql_free_result($result);
? >
< /form >

Most of ml_quick_msg.php is HTML, and the PHP code that is used is practically identical to the
code used to build the select in
ml_admin.php .
< form method=”post” action=”ml_admin_transact.php” >
< table >
< tr >
< td > < label for=”ml_id” > Mailing List: < /label > < /td >
< td > < select name=”ml_id” id=”ml_id” >
< option value=”all” > All < /option >
< ?php
$query = ‘SELECT ml_id, listname FROM ml_lists ORDER BY listname’;
c14.indd 482c14.indd 482 12/10/08 6:02:32 PM12/10/08 6:02:32 PM
Chapter 14: Mailing Lists
483
$result = mysql_query($query, $db) or die(mysql_error($db));

while ($row = mysql_fetch_array($result)) {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” > ’ . $row[‘listname’] .
‘ < /option > ’;
}
mysql_free_result($result);
? >
< /select > < /td >
< /tr > < tr >

< td > < label for=”subject” > Subject: < /label > < /td >
< td > < input type=”text” name=”subject” id=”subject”/ > < /td >
< /tr > < tr >
< td > < label for=”message” > Message: < /label > < /td >
< td > < textarea name=”message” id=”message” rows=”10”
cols=”60” > < /textarea > < /td >
< /tr > < tr >
< td > < /td
>
< td > < input type=”submit” name=”action” value=”Send Message”/ > < /td >
< /tr > < tr >
< /table >
< /form >

Finally, you come to the real workhorse of the mailing list administrator application, admin_
transact.php
. This page is the one to which you post your forms; it will process the information,
update the database tables, and send out e - mails as required. It uses the
SimpleMail class from
Chapter 11 to send e - mail. If you are scratching your head and trying to remember exactly how the
class works, then now would be a good time to take a break and review
class.SimpleMail.php .
require ‘class.SimpleMail.php’;

Did the user click an “ action ” button? You filter the incoming value of $_POST[ ‘ action ’ ] and then
act on the value accordingly, using a
switch statement. Depending on which button was clicked,
you ’ re going to perform one of three actions: create a new mailing list, delete an old mailing list, or
send a message to the users subscribed to a list.
$action = (isset($_POST[‘action’])) ? $_POST[‘action’] : ‘’;


switch ($action) {
case ‘Add New Mailing List’:

break;

case ‘Delete Mailing List’:

break;

case ‘Send Message’:

break;
}

c14.indd 483c14.indd 483 12/10/08 6:02:33 PM12/10/08 6:02:33 PM
484
Part II: Comic Book Fan Site
To add a new mailing list, you filter the incoming list name and insert a new record into the
ml_lists table.
case ‘Add New Mailing List’:
$listname = isset($_POST[‘listname’]) ? $_POST[‘listname’] : ‘’;
if (!empty($listname)) {
$query = ‘INSERT INTO ml_lists
(listname)
VALUES
(“’ . mysql_real_escape_string($listname, $db) . ‘”)’;
mysql_query($query, $db) or die(mysql_error($db));
}
break;


Deleting a mailing list is only slightly more complex. Not only must you delete the mailing list itself,
but you must also delete any subscriptions to the list.
case ‘Delete Mailing List’:
$ml_id = isset($_POST[‘ml_id’]) ? $_POST[‘ml_id’] : ‘’;
if (ctype_digit($ml_id)) {
$query = ‘DELETE FROM ml_lists WHERE ml_id=’ . $ml_id;
mysql_query($query, $db) or die(mysql_error($db));

$query = ‘DELETE FROM ml_subscriptions WHERE ml_id=’ . $ml_id;
mysql_query($query, $db) or die(mysql_error($db));
}
break;

The form in ml_quick_msg.php posts the mailing list as the mailing list ’ s ID, which — while great for

ml_admin_transact.php — isn ’ t of much use to the subscriber. When you send a message, you want
to let the user know which mailing list you are referring to. If the mailing list ID is
‘ all ’ instead of a
number, you want to reflect that as well:
case ‘Send Message’:
$ml_id = isset($_POST[‘ml_id’]) ? $_POST[‘ml_id’] : ‘’;
$subject = isset($_POST[‘subject’]) ? $_POST[‘subject’] : ‘’;
$message = isset($_POST[‘message’]) ? $_POST[‘message’] : ‘’;

if ($ml_id == ‘all’) {
$listname = ‘Master’;
} else if (ctype_digit($ml_id)) {
$query = ‘SELECT
listname

FROM
ml_lists
WHERE
ml_id=’ . $ml_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
$listname = $row[‘listname’];
mysql_free_result($result);
} else {
break;
}

c14.indd 484c14.indd 484 12/10/08 6:02:33 PM12/10/08 6:02:33 PM
Chapter 14: Mailing Lists
485
What follows is a more complicated SQL statement than you ’ ve written thus far, but not too
difficult. What ’ s happening here is that you are grabbing the e - mails, first names, and user IDs from the

ml_users table where the mailing list ID ( ml_id ) matches their user ID in the ml_subscriptions table.
You do this by using the
INNER JOIN command in SQL. You also don ’ t want to send any e - mails to those
that are awaiting subscription confirmation, so select only those where
pending = FALSE .
If the administrator did not choose
‘ all ’ in the select list, you must limit your selection to the specific
users that are subscribed to the mailing list the administrator selected. You do this by adding on the

AND condition.
$query = ‘SELECT DISTINCT
u.user_id, u.first_name, u.email

FROM
ml_users u INNER JOIN ml_subscriptions s ON
u.user_id = s.user_id
WHERE
s.pending = FALSE’;
if ($ml_id != ‘all’) {
$query .= ‘ AND s.ml_id = ‘ . $ml_id;
}
$result = mysql_query($query, $db) or die(mysql_error($db));

Finally, you iterate through the returned records with a while loop. Within the loop, you append a
footer to the message that will be sent out, explaining how the user can unsubscribe from the mailing
list, if he or she wants to. Then you create a new instance of the
SimpleMail class and set the relevant
options, and then the message can be sent on its way.
Notice that you are looping through each e - mail address you have and sending an e - mail to each one,
using the
send() method. It is important to note that the page will not finish loading until it has sent
every e - mail. This works fine if you have a few e - mail addresses (a few hundred or less). It has the
added benefit of allowing you to personalize each e - mail.
If you need to send to more people and don ’ t want to deal with the long wait time, we recommend
putting all of your e - mail addresses in the BCC: field of the mail. You can ’ t personalize the e - mail, but
the page will load much faster.
while ($row = mysql_fetch_assoc($result)) {

$footer = “\n\n” . ‘ ’ . “\n”;
if (ctype_digit($ml_id)) {
$footer .= ‘You are receiving this message as a member ‘ .
‘of the ‘ . $listname . “\n”;
$footer .= ‘mailing list. If you have received this ‘ .

‘email in error or would like to’ . “\n”;
$footer .= ‘remove your name from this mailing list, ‘ .
‘please visit the following URL:’ . “\n”;
$footer .= ‘ .
$row[‘user_id’] . “ & ml=” . $ml_id;
} else {
$footer .= ‘You are receiving this email because you ‘ .
‘subscribed to one or more’ . “\n”;
$footer .= ‘mailing lists. Visit the following URL to ‘ .
‘change your subscriptions:’ . “\n”;
c14.indd 485c14.indd 485 12/10/08 6:02:33 PM12/10/08 6:02:33 PM
486
Part II: Comic Book Fan Site
$footer .= ‘ .
$row[‘user_id’];
}

$mail = new SimpleMail();

$mail- > setToAddress($row[‘email’]);
$mail- > setFromAddress(‘’);
$mail- > setSubject($subject);
$mail- > setTextBody($message . $footer);

$mail- > send();
}
mysql_free_result($result);
break;

After the page is done with its transactions, it redirects the user to the ml_admin.php page.

header(‘Location: ml_admin.php’);
Sign Me Up!
Now it ’ s time to look at the other half of the application, the Mailing List sign - up form. This is the page
your users will use to sign up for any of the mailing lists that you have created. This portion of the
application consists of
ml_user.php , ml_user_transact.php , ml_thanks.php , and ml_remove.php .
Try It Out Mailing List Signup
The first task in coding this portion of the application is to create the scripts necessary to sign up
subscribers. You will be coding
ml_user.php , ml_user_transact.php , and ml_transact.php . You
will code
ml_remove.php later.
1. Enter the following code in your editor, and save it as ml_user.php :
< ?php
require ‘db.inc.php’;

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect. Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

$user_id = (isset($_GET[‘user_id’]) & & ctype_digit($_GET[‘user_id’])) ?
$_GET[‘user_id’] : ‘’;

$first_name = ‘’;
c14.indd 486c14.indd 486 12/10/08 6:02:33 PM12/10/08 6:02:33 PM
Chapter 14: Mailing Lists
487
$last_name = ‘’;
$email = ‘’;

$ml_ids = array();

if (!empty($user_id)) {
$query = ‘SELECT
first_name, last_name, email
FROM
ml_users
WHERE
user_id = ‘ . $user_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
extract($row);
}
mysql_free_result($result);

$query = ‘SELECT ml_id FROM ml_subscriptions WHERE user_id = ‘ . $user_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
$ml_ids[] = $row[‘ml_id’];
}
mysql_free_result($result);
}
? >
< html >
< head >
< title > Mailing List Signup < /title >
< /head >
< body >
< h1 > Sign up for Mailing List: < /h1 >

< form method=”post” action=”ml_user_transact.php” >
< table >
< tr >
< td > < label for=”email” > Email Address: < /label > < /td >
< td > < input type=”text” name=”email” id=”email” value=” < ?php echo
$email; ? > ”/ >
< /td >
< /tr >
< /table >
< p > If you aren’t currently a member, please provide your name: < /p >

< table >
< tr >
< td > < label for=”first_name” > First Name: < /label > < /td >
< td > < input type=”text” name=”first_name” id=”first_name”
value=” < ?php echo $first_name; ? > ”/ > < /td >
< /tr > < tr >
< td > < label for=”last_name” > Last Name: < /label > < /td >
< td > < input type=”text” name=”last_name” id=”last_name”
value=” < ?php echo $last_name; ? > ”/ > < /td >
< /tr >
< /table >
c14.indd 487c14.indd 487 12/10/08 6:02:34 PM12/10/08 6:02:34 PM
488
Part II: Comic Book Fan Site
< p > Select the mailing lists you want to receive: < /p >
< p >
< select name=”ml_id[]” multiple=”multiple” >
< ?php
$query = ‘SELECT

ml_id, listname
FROM
ml_lists
ORDER BY
listname ASC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

print_r($ml_ids);
while ($row = mysql_fetch_array($result)) {
if (in_array($row[‘ml_id’], $ml_ids)) {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” selected=”selected” > ’;
} else {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” > ’;
}
echo $row[‘listname’] . ‘ < /option > ’;
}
mysql_free_result($result);
? >
< /select >
< /p >
< p > < input type=”submit” name=”action” value=”Subscribe” / > < /p >
< /form >
< /body >
< /html >
2. Enter the transaction page by entering the following and saving it as ml_user_transact
.php
:
< ?php
require ‘db.inc.php’;
require ‘class.SimpleMail.php’;


$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect. Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

$action = (isset($_REQUEST[‘action’])) ? $_REQUEST[‘action’] : ‘’;

switch ($action) {
case ‘Subscribe’:
$email = (isset($_POST[‘email’])) ? $_POST[‘email’] : ‘’;
$query = ‘SELECT
user_id
FROM
ml_users
c14.indd 488c14.indd 488 12/10/08 6:02:34 PM12/10/08 6:02:34 PM
Chapter 14: Mailing Lists
489
WHERE
email=”’ . mysql_real_escape_string($email, $db) . ‘”’;
$result = mysql_query($query, $db) or die(mysql_error($db));

if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$user_id = $row[‘user_id’];
} else {
$first_name = (isset($_POST[‘first_name’])) ?
$_POST[‘first_name’] : ‘’;
$last_name = (isset($_POST[‘last_name’])) ?
$_POST[‘last_name’] : ‘’;


$query = ‘INSERT INTO ml_users
(first_name, last_name, email)
VALUES
(“’ . mysql_real_escape_string($first_name, $db) . ‘”, ‘ .
‘”’ . mysql_real_escape_string($last_name, $db) . ‘”, ‘ .
‘”’ . mysql_real_escape_string($email, $db) . ‘”)’;
mysql_query($query, $db);
$user_id = mysql_insert_id($db);
}
mysql_free_result($result);

foreach ($_POST[‘ml_id’] as $ml_id) {
if (ctype_digit($ml_id)) {
$query = ‘INSERT INTO ml_subscriptions
(user_id, ml_id, pending)
VALUES
(‘ . $user_id . ‘, ‘ . $ml_id . ‘, TRUE)’;
mysql_query($query, $db);

$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ .
$ml_id;
$result = mysql_query($query, $db);

$row = mysql_fetch_assoc($result);
$listname = $row[‘listname’];

$message = ‘Hello ‘ . $first_name . “\n” .
$message .= ‘Our records indicate that you have subscribed ‘ .
‘to the ‘ . $listname . ‘ mailing list.’ . “\n\n”;

$message .= ‘If you did not subscribe, please accept our ‘ .
‘apologies. You will not be subscribed if you do ‘ .
‘not visit the confirmation URL.’ . “\n\n”;
$message .= ‘If you subscribed, please confirm this by ‘ .
‘visiting the following URL: ‘ .
‘ .
$user_id . ‘ & ml_id=’ . $ml_id . ‘ & action=confirm’;

$mail = new SimpleMail();
c14.indd 489c14.indd 489 12/10/08 6:02:34 PM12/10/08 6:02:34 PM
490
Part II: Comic Book Fan Site
$mail- > setToAddress($email);
$mail- > setFromAddress(‘’);
$mail- > setSubject(‘Mailing list confirmation’);
$mail- > setTextBody($message);
$mail- > send();
unset($mail);
}
}
header(‘Location: ml_thanks.php?user_id=’ . $user_id . ‘ & ml_id=’ .
$ml_id . ‘ & type=c’);
break;

case ‘confirm’:
$user_id = (isset($_GET[‘user_id’])) ? $_GET[‘user_id’] : ‘’;
$ml_id = (isset($_GET[‘ml_id’])) ? $_GET[‘ml_id’] : ‘’;

if (!empty($user_id) & & !empty($ml_id)) {
$query = ‘UPDATE ml_subscriptions

SET
pending = FALSE
WHERE
user_id = ‘ . $user_id . ‘ AND
ml_id = ‘ . $ml_list;
mysql_query($query, $db);

$query = ‘SELECT
listname
FROM
ml_lists
WHERE
ml_id = ‘ . $ml_id;
$result = mysql_query($query, $db);

$row = mysql_fetch_assoc($result);
$listname = $row[‘listname’];
mysql_free_result($result);

$query = ‘SELECT
first_name, email
FROM
ml_users
WHERE
user_id = ‘ . $user_id;
$result = mysql_query($query, $db);

$row = mysql_fetch_assoc($result);
$first_name = $row[‘first_name’];
$email = $row[‘email’];

mysql_free_result($result);

$message = ‘Hello ‘ . $first_name . ‘,’ . “\n”;
c14.indd 490c14.indd 490 12/10/08 6:02:35 PM12/10/08 6:02:35 PM
Chapter 14: Mailing Lists
491
$message .= ‘Thank you for subscribing to the ‘ . $listname .
‘ mailing list. Welcome!’ . “\n\n”;
$message .= ‘If you did not subscribe, please accept our ‘ .
‘apologies. You can remove’ . “\n”;
$message .= ‘this subscription immediately by visiting the ‘ .
‘following URL:’ . “\n”;
$message .= ‘ .
$user_id . ‘ & ml_id=’ . $ml_id;

$mail = new SimpleMail();
$mail- > setToAddress($email);
$mail- > setFromAddress(‘’);
$mail- > setSubject(‘Mailing list subscription confirmed’);
$mail- > setTextBody($message);
$mail- > send();

header(‘Location: ml_thanks.php?user_id=’ . $user_id . ‘ & ml_id=’ .
$ml_id . ‘ & type=s’);
} else {
header(‘Location: ml_user.php’);
}
break;
}
? >

3. You may have noticed when entering the last script that you are redirecting your users to a
page called
ml_thanks.php . It would probably be a good idea to create that page now, by
entering the following code and saving it as
ml_thanks.php :
< html >
< head >
< title > Thank You < /title >
< /head >
< body >
< ?php
require ‘db.inc.php’;

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect. Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

$user_id = (isset($_GET[‘user_id’])) ? $_GET[‘user_id’] : ‘’;
$ml_id = (isset($_GET[‘ml_id’])) ? $_GET[‘ml_id’] : ‘’;
$type = (isset($_GET[‘type’])) ? $_GET[‘type’] : ‘’;

if (empty($user_id)) {
die(‘No user id available.’);
}
c14.indd 491c14.indd 491 12/10/08 6:02:35 PM12/10/08 6:02:35 PM
492
Part II: Comic Book Fan Site
$query = ‘SELECT first_name, email FROM ml_users WHERE user_id = ‘ .
$user_id;

$result = mysql_query($query, $db) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$first_name = $row[‘first_name’];
$email = $row[‘email’];
} else {
die(‘No match for user id.’);
}
mysql_free_result($result);

if (empty($ml_id)) {
die(‘No mailing list id available.’);
}
$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ . $ml_id;
$result = mysql_query($query, $db) or die(mysql_error());

if (mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
$listname = $row[‘listname’];
} else {
die (‘No match for mailing list id’);
}
mysql_free_result($result);

if ($type == ‘c’) {
echo ‘ < h1 > Thank You ‘ . $first_name . ‘ < /h1 > ’;
echo ‘ < p > A confirmation for subscribing to the ‘ . $listname .
‘ mailing list ‘ .
‘has been sent to ‘ . $email . ‘. < /p > ’;

} else {
echo ‘ < h1 > Thank You ‘ . $first_name . ‘ < /h1 > ’;
echo ‘ < p > Thank you for subscribing to the ‘ . $listname . ‘
mailing list. < /p > ’;
}
? >
< /body >
< /html >
c14.indd 492c14.indd 492 12/10/08 6:02:35 PM12/10/08 6:02:35 PM
Chapter 14: Mailing Lists
493
4. Open your browser, and open ml_user.php . You should see a form that looks very much like
the one in Figure 14 - 3 .
Figure 14-3
5. Enter your e - mail address and your first and last name, choose one or more mailing lists to
subscribe to, and click Subscribe.
You should see a Thank You screen (shown in Figure 14 - 4 ) and receive a confirmation e - mail
at the e - mail address you supplied.
c14.indd 493c14.indd 493 12/10/08 6:02:36 PM12/10/08 6:02:36 PM
494
Part II: Comic Book Fan Site
6. Open the confirmation e - mail. There will be a link at the bottom (or a non - linked URL, if you
are using a text e - mail client).
7. Click the link, and it takes you back to the Thank You page, this time thanking you for
confirming your subscription. You will get another e - mail informing you about your
subscription, with a link that allows you to remove yourself from the mailing list. Don ’ t click
that link just yet!
8. Open ml_admin.php , and then click the link at the bottom, “ Send a quick message to users. ”
9. In the Quick Message page, choose a mailing list that you just subscribed to in the previous
steps, and enter a subject. Then type a quick message.

10. Click Send Message.
11. Open your e - mail client again, and read the message you should have received.
Figure 14-4
c14.indd 494c14.indd 494 12/10/08 6:02:36 PM12/10/08 6:02:36 PM
Chapter 14: Mailing Lists
495
How It Works
Excellent job! Now that you ’ ve written and tested your code, it ’ s time for us to explain how it all
works. Typically,
ml_user.php will display a blank form. Occasionally, you may want the fields to be
populated with the subscriber ’ s information, and so you pass the user ID of the subscriber along in
the URL.
ml_user.php will use the ID to look up the information in the database and pre - populate
the form ’ s fields.
You filter the incoming user ID (if it appears in the URL) and initialize the variables that are used in
displaying the form to blank values:
$user_id = (isset($_GET[‘user_id’]) & & ctype_digit($_GET[‘user_id’])) ?
$_GET[‘user_id’] : ‘’;

$first_name = ‘’;
$last_name = ‘’;
$email = ‘’;
$ml_ids = array();

If a user ’ s ID has been supplied, then you retrieve the information from the database and populate the
variables you just initialized:
if (!empty($user_id)) {
$query = ‘SELECT
first_name, last_name, email
FROM

ml_users
WHERE
user_id = ‘ . $user_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
extract($row);
}
mysql_free_result($result);

$query = ‘SELECT ml_id FROM ml_subscriptions WHERE user_id = ‘ .
$user_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
$ml_ids[] = $row[‘ml_id’];
}
mysql_free_result($result);
}

Displaying the fields to collect the subscriber ’ s e - mail address, first name, and last name is pretty
straightforward. You output the variables ’ contents for the field ’ s
value attributes, so if a user ID has
been provided, then the fields will appear pre - populated. Since the variables were initialized with
blank default values, the fields will be empty if no valid user ID has been received.
You need to again query the database when you display the
select field. You retrieve all the IDs and
names of the mailing lists, and then iterate through them to generate the
select ’ s options. During
c14.indd 495c14.indd 495 12/10/08 6:02:37 PM12/10/08 6:02:37 PM
496

Part II: Comic Book Fan Site
each run through the loop, you check the current record ’ s ml_id to see if the user is subscribed to it,
and if so, then you set the option as selected, so all of the lists the user is subscribed to will be selected
when the form is pre - populated.
< select name=”ml_id[]” multiple=”multiple” >
< ?php
$query = ‘SELECT
ml_id, listname
FROM
ml_lists
ORDER BY
listname ASC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

print_r($ml_ids);
while ($row = mysql_fetch_array($result)) {
if (in_array($row[‘ml_id’], $ml_ids)) {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” selected=”selected” > ’;
} else {
echo ‘ < option value=”’ . $row[‘ml_id’] . ‘” > ’;
}
echo $row[‘listname’] . ‘ < /option > ’;
}
mysql_free_result($result);
? >
< /select >

The ml_thanks.php is almost not worth mentioning because its PHP code is something you should
already be familiar with at this point. It accepts the subscriber ’ s user ID (
user_id ), the ID of the

mailing list he or she subscribed to (
ml_id ), and the type of thank you message it should display
(
type ) from the URL. After filtering them, the page displays the appropriate thank you message to the
subscriber.
The real action happens in
ml_user_transact.php , which handles creating and updating
subscribers ’ records in the database.
You filter the incoming value of
$_REQUEST[ ‘ action ’ ] and then act on the value accordingly,
using a
switch statement. Depending on which action is requested, you either subscribe a user to a
mailing list or confirm a user ’ s subscription.
$action = (isset($_REQUEST[‘action’])) ? $_REQUEST[‘action’] : ‘’;

switch ($action) {
case ‘Subscribe’:

break;

case ‘confirm’:

break;
}

If the user was sent to ml_user_transact.php because he or she clicked the Subscribe button of

ml_user.php ’ s form, you subscribe him or her to the appropriate lists. A number of things have to be
c14.indd 496c14.indd 496 12/10/08 6:02:37 PM12/10/08 6:02:37 PM
Chapter 14: Mailing Lists

497
done for this to happen. First, you must look up the e - mail address that was provided, to see if the
user already exists in the
ml_user table and retrieve the user ’ s ID. If the user doesn ’ t exist, then you
create a new record for the user, including his or her first and last name. Once a record is created, then
you use
mysql_insert_id() to retrieve the user ’ s ID.
case ‘Subscribe’:
$email = (isset($_POST[‘email’])) ? $_POST[‘email’] : ‘’;
$query = ‘SELECT
user_id
FROM
ml_users
WHERE
email=”’ . mysql_real_escape_string($email, $db) . ‘”’;
$result = mysql_query($query, $db) or die(mysql_error($db));

if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$user_id = $row[‘user_id’];
} else {
$first_name = (isset($_POST[‘first_name’])) ?
$_POST[‘first_name’] : ‘’;
$last_name = (isset($_POST[‘last_name’])) ?
$_POST[‘last_name’] : ‘’;

$query = ‘INSERT INTO ml_users
(first_name, last_name, email)
VALUES
(“’ . mysql_real_escape_string($first_name, $db) . ‘”, ‘ .

‘”’ . mysql_real_escape_string($last_name, $db) . ‘”, ‘ .
‘”’ . mysql_real_escape_string($email, $db) . ‘”)’;
mysql_query($query, $db);
$user_id = mysql_insert_id($db);
}
mysql_free_result($result);

Then you loop through each mailing list the user wants to subscribe to, and create an entry in the

ml_subscriptions table that links the user ’ s ID to the list ’ s ID. The record ’ s status is also set to
pending at this point, with
pending set to TRUE .
You send the new user an e - mail informing him or her of the new subscription, using the
SimpleMail
class from Chapter 11 . The subscription will not be active until the user visits a link you provide in the
e - mail for the user to confirm the subscription.
foreach ($_POST[‘ml_id’] as $ml_id) {
if (ctype_digit($ml_id)) {
$query = ‘INSERT INTO ml_subscriptions
(user_id, ml_id, pending)
VALUES
(‘ . $user_id . ‘, ‘ . $ml_id . ‘, TRUE)’;
mysql_query($query, $db);

$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ .
$ml_id;
c14.indd 497c14.indd 497 12/10/08 6:02:37 PM12/10/08 6:02:37 PM
498
Part II: Comic Book Fan Site
$result = mysql_query($query, $db);


$row = mysql_fetch_assoc($result);
$listname = $row[‘listname’];

$message = ‘Hello ‘ . $first_name . “\n” .
$message .= ‘Our records indicate that you have subscribed ‘ .
‘to the ‘ . $listname . ‘ mailing list.’ . “\n\n”;
$message .= ‘If you did not subscribe, please accept our ‘ .
‘apologies. You will not be subscribed if you do ‘ .
‘not visit the confirmation URL.’ . “\n\n”;
$message .= ‘If you subscribed, please confirm this by ‘ .
‘visiting the following URL: ‘ .
‘ .
$user_id . ‘ & ml_id=’ . $ml_id . ‘ & action=confirm’;

$mail = new SimpleMail();
$mail- > setToAddress($email);
$mail- > setFromAddress(‘’);
$mail- > setSubject(‘Mailing list confirmation’);
$mail- > setTextBody($message);
$mail- > send();
unset($mail);
}
}
header(‘Location: ml_thanks.php?user_id=’ . $user_id . ‘ & ml_id=’ .
$ml_id . ‘ & type=c’);

When the user visits the link you provided in the confirmation e - mail, he or she should be taken
to
ml_user_transact.php , and the “ confirm ” branch of the switch statement is executed.

Here is where you validate the incoming user ID and list ID and update the user ’ s records in
the
ml_subscriptions table, so the subscription is no longer marked pending. You then retrieve the
user ’ s first name and e - mail address, to send another e - mail to inform him or her of the subscription ’ s
change in status.
case ‘confirm’:
$user_id = (isset($_GET[‘user_id’])) ? $_GET[‘user_id’] : ‘’;
$ml_id = (isset($_GET[‘ml_id’])) ? $_GET[‘ml_id’] : ‘’;

if (!empty($user_id) & & !empty($ml_id)) {
$query = ‘UPDATE ml_subscriptions
SET
pending = FALSE
WHERE
user_id = ‘ . $user_id . ‘ AND
ml_id = ‘ . $ml_id;
mysql_query($query, $db);

$query = ‘SELECT
listname
c14.indd 498c14.indd 498 12/10/08 6:02:37 PM12/10/08 6:02:37 PM
Chapter 14: Mailing Lists
499
FROM
ml_lists
WHERE
ml_id = ‘ . $ml_id;
$result = mysql_query($query, $db);

$row = mysql_fetch_assoc($result);

$listname = $row[‘listname’];
mysql_free_result($result);

$query = ‘SELECT
first_name, email
FROM
ml_users
WHERE
user_id = ‘ . $user_id;
$result = mysql_query($query, $db);

$row = mysql_fetch_assoc($result);
$first_name = $row[‘first_name’];
$email = $row[‘email’];
mysql_free_result($result);

$message = ‘Hello ‘ . $first_name . ‘,’ . “\n”;
$message .= ‘Thank you for subscribing to the ‘ . $listname .
‘ mailing list. Welcome!’ . “\n\n”;
$message .= ‘If you did not subscribe, please accept our ‘ .
‘apologies. You can remove’ . “\n”;
$message .= ‘this subscription immediately by visiting the ‘ .
‘following URL:’ . “\n”;
$message .= ‘ .
$user_id . ‘ & ml_id=’ . $ml_id;

$mail = new SimpleMail();
$mail- > setToAddress($email);
$mail- > setFromAddress(‘’);
$mail- > setSubject(‘Mailing list subscription confirmed’);

$mail- > setTextBody($message);
$mail- > send();

header(‘Location: ml_thanks.php?user_id=’ . $user_id . ‘ & ml_id=’ .
$ml_id);
} else {
header(‘Location: ml_user.php’);
}
break;
c14.indd 499c14.indd 499 12/10/08 6:02:38 PM12/10/08 6:02:38 PM
500
Part II: Comic Book Fan Site
Try It Out Removing Your Subscription
Now that you ’ ve given users the ability to add themselves to your mailing lists, you need to give them
the ability to remove themselves, if they want. The e - mails that you send have a link allowing your
users to remove themselves from the mailing lists, if they so desire.
1. Enter this code, and save it as ml_remove.php :
< html >
< head >
< title > Remove Subscription < /title >
< /head >
< body >
< h1 > Remove Subscription < /h1 >
< ?php
require ‘db.inc.php’;

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect. Check your connection parameters.’);

mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));


$user_id = (isset($_GET[‘user_id’]) & & ctype_digit($_GET[‘user_id’])) ?
$_GET[‘user_id’] : -1;

$ml_id = (isset($_GET[‘ml_id’]) & & ctype_digit($_GET[‘ml_id’])) ?
$_GET[‘ml_id’] : -1;

if (empty($user_id) || empty($ml_id)) {
die(‘Incorrect parameters passed.’);
}
$query = ‘DELETE FROM ml_subscriptions WHERE user_id = ‘ . $user_id . ‘
AND ml_id = ‘ . $ml_id;
mysql_query($query, $db) or die(mysql_error());

$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ . $ml_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) == 0) {
die(‘Unknown list.’);
}
$row = mysql_fetch_array($result);
$listname = $row[‘listname’];
mysql_free_result($result);

echo ‘ < p > You have been removed from the ‘ . $listname . ‘ mailing list < /p > ’;
echo ‘ < p > < a href=”ml_user.php?user_id=’ . $user_id . ‘” > Return to Mailing ‘ .
‘List Signup page. < /a > < /p > ’;
? >
< /body >
< /html >
c14.indd 500c14.indd 500 12/10/08 6:02:38 PM12/10/08 6:02:38 PM

Chapter 14: Mailing Lists
501
2. Go back to the e - mail you sent yourself earlier, and find the link at the bottom of it. Click it
to remove yourself from the mailing list. You should see the Removal page, as shown in
Figure 14 - 5 . If you send another message to that mailing list, then that message should not be
sent to your e - mail address.
Figure 14-5
How It Works
Users can remove themselves from a mailing list by following the link at the bottom of any e - mail they
receive from the list. The link directs the user to the
ml_remove.php page, which requires two
parameters, the user ’ s ID and the mailing list ’ s ID, to be supplied in the URL.
You take in and filter the user ’ s ID and the list ’ s ID, and then use them in a
DELETE query against the

ml_subscriptions table, to remove the user ’ s subscription.
$user_id = (isset($_GET[‘user_id’]) & & ctype_digit($_GET[‘user_id’])) ?
$_GET[‘user_id’] : -1;

$ml_id = (isset($_GET[‘ml_id’]) & & ctype_digit($_GET[‘ml_id’])) ?
$_GET[‘ml_id’] : -1;

if (empty($user_id) || empty($ml_id)) {
die(‘Incorrect parameters passed.’);
}
$query = ‘DELETE FROM ml_subscriptions WHERE user_id = ‘ . $user_id . ‘
AND ml_id = ‘ . $ml_id;
mysql_query($query, $db) or die(mysql_error());

c14.indd 501c14.indd 501 12/10/08 6:02:38 PM12/10/08 6:02:38 PM

502
Part II: Comic Book Fan Site
Afterwards, you retrieve the name of the mailing list from the ml_lists table and use it to display a
message telling the user that the removal has taken place.
$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ . $ml_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) == 0) {
die(‘Unknown list.’);
}
$row = mysql_fetch_array($result);
$listname = $row[‘listname’];
mysql_free_result($result);

echo ‘ < p > You have been removed from the ‘ . $listname . ‘ mailing list < /p > ’;
echo ‘ < p > < a href=”ml_user.php?user_id=’ . $user_id . ‘” > Return to Mailing ‘ .
‘List Signup page. < /a > < /p > ’;




Mailing List Ethics
You should know about a couple of ethical issues when dealing with the world of mailing lists, namely
spam and opt - in/opt - out. This section represents our personal soap box for airing our opinions about
them. Although these are our opinions, however, you may want to pay close attention.
A Word about Spam
With the advent of the computer, mailing lists have been brought to a whole new level. Now you can
be (and no doubt are) told on a daily basis that Sally really wants you to visit her web site, and that a
little blue pill will solve all of your personal problems. Yes, occasionally an e - mail sits in your inbox
informing you of new job postings, new posts on PHPBuilder.com , or tour dates for Jimmy Buffett. But
we think you know what mailing lists are primarily used for: spam!

For those of you just crawling out of a suspended animation chamber, spam is a term used to describe a
shotgun approach to advertising. You simply send your e - mail advertisement to as many people as you
possibly can, in the hopes that a certain small percentage of them will actually respond.
What is our point? SPAM is a luncheon meat. You spell it in all capital letters, and you enjoy it on your
sandwiches. Spam, on the other hand isn ’ t so tasty. It ’ s another name for unsolicited commercial e - mail.
It is spelled in all lowercase, and we shun it.
The bottom line: Don ’ t use mailing lists to send spam. Your mother would be very disappointed.
c14.indd 502c14.indd 502 12/10/08 6:02:39 PM12/10/08 6:02:39 PM
Chapter 14: Mailing Lists
503
Opt - In versus Opt - Out
You may have heard the terms opt - in and opt - out before. What do they mean? To most of your users,
probably not much. Users simply answer the questions on your registration, read the fine print, and click
the Submit button. However, you aren ’ t a user anymore — at least, not on your own site. You are the
administrator. You need to understand the difference between opt - in and opt - out because it may mean
the difference between annoyance and acceptance from your users.
Opt - in and opt - out are fancy ways of asking, “ What is the default choice for your users? ” Opt - in means
the user is not currently scheduled to receive a specific newsletter, but he or she may opt to subscribe.
Obviously, opt - out is the opposite — your user will automatically receive notifications unless he or she
opts to remove him - or herself from that mailing list.
Why the difference? As the administrator, you may sometimes have to walk a fine line between
satisfying your advertisers (the ones that might be giving you money to keep your site alive) and your
users (the ones visiting your site, keeping your advertisers happy by driving up the number of hits).
If an advertiser pays you enough, you might agree to automatically send advertisements from that
company unless the user explicitly chooses not to receive them (opt - out).
However, you might have a newsletter you send once per week that contains, for example, details of
comic conventions throughout the country (or even the world). Not all visitors to your site will be
interested in that, but if any are, they can subscribe to the newsletter so they will always be notified
(opt - in).
As we mentioned, you walk a fine line when choosing between the two. Because this is a new web site

for you, the decision might not be that difficult. But as your site grows, interest increases, and companies
want to advertise with you, you ’ ll need to make these important decisions. For now, we suggest you
make all mailing lists opt - in, with the exception of important site announcements.
Summary
You have just created a nice, relatively simple mailing list subscription application. You have the ability
to create new mailing lists, delete old ones, and send e - mails to multiple recipients. Users can subscribe
to and unsubscribe from any mailing lists, and you added a step for confirmation to help stamp out
abuse.
We hope you come away from this chapter with an understanding of the difference between good,
informative mass e - mails and spam.
Mailing lists are good. Spam is bad. Any questions? Good. Next, we ’ ll take a look at how to sell your
SPAM collection on your web site.
c14.indd 503c14.indd 503 12/10/08 6:02:39 PM12/10/08 6:02:39 PM
504
Part II: Comic Book Fan Site
Exercises
1. Hide your users ’ addresses: Modify the send message functionality to send the e - mails to your
users, using the BCC: e - mail field, instead of the usual To: field.
2. Reduce sending: Modify the send message functionality to send e - mails to your users in groups
of 10. That is, every e - mail that is sent should be sent to 10 users at a time (when possible),
instead of one e - mail per user.
3. Let the administrator know: Add functionality to send an e - mail to an administrator when new
users confirm their subscription to the mailing list.
4. Clean up any leftovers: Add functionality to the administration page to allow an admin to
purge the database of any subscriptions that haven ’ t yet been confirmed.

c14.indd 504c14.indd 504 12/10/08 6:02:39 PM12/10/08 6:02:39 PM
15
Online Stores
Some of us cringe when we hear the word “ e - commerce ” and the phrase “ selling over the

Internet. ” Perhaps we ’ ve had a bad experience ourselves, or the thought of opening an online store
is just too overwhelming. Even though this is the part of the book that all geeks out there probably
dread reading, we ’ re here to show you that e - commerce is nothing to fear and that pretty much
anyone can do it.
However, the fact that anyone can do it doesn ’ t mean it ’ s always done the right way. Done the
wrong way, your site can look downright cheesy. Done the right way, your site can look
professional and inviting and become an excellent resource for your visitors and potential
customers. There are definite guidelines for selling things over the web, and we want to make sure
you do things the right way.
Selling things from your web site can not only put some extra cash in your pocket, but it can
enhance your relationship with your web site visitors as well, even if e - commerce is not your site ’ s
primary function. In the case of your comic book fan site, offering pertinent items can make your
site more interactive and interesting. It can bring in new visitors who may not have known about
your site before, and keep visitors coming back to see what new items you have for sale. True
comic book fans will appreciate the niche of items you are providing, especially if some of the
items are unique or hard to come by.
This chapter discusses the following:
Creating a simple shopping - cart script .
Ideas to improve your script .
The basics of e - commerce .



c15.indd 505c15.indd 505 12/10/08 6:03:13 PM12/10/08 6:03:13 PM

×