1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning PHP6, Apache, MySQL Web Development- P18 pot

30 296 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Mailing Lists
Trường học Standard University
Chuyên ngành Web Development
Thể loại Bài luận
Năm xuất bản 2008
Thành phố City Name
Định dạng
Số trang 30
Dung lượng 486,75 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 us

Trang 1

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

Trang 2

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

p < label for=”listname” > Add Mailing List: < /label > < br / >

/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

echo ‘ < > < label for=”ml_id” > Delete Mailing List: < /label > < br / >

echo ‘ < select name=”ml_id” id=”ml_id” >

while ($row = mysql_fetch_array($result)) {

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

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’;

Trang 3

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

while ($row = mysql_fetch_array($result)) {

‘ < /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”

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;

}

Trang 4

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’] : ‘’;

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’] : ‘’;

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’] : ‘’;

Trang 5

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 = ‘http://www.example.com/ml_remove.php?user_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”;

Trang 6

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.’);

Trang 7

ml_users WHERE

$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);

< 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

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

Trang 8

< > Select the mailing lists you want to receive: < /p >

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or

die (‘Unable to connect Check your connection parameters.’);

Trang 9

WHERE email=”’ mysql_real_escape_string($email, $db) ‘”’;

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

$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: ‘

‘http://example.com/ml_user_transact.php?user_id=’ $user_id ‘ & ml_id=’ $ml_id ‘ & action=confirm’;

$mail = new SimpleMail();

Trang 10

$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

Trang 11

$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 = ‘http://example.com/ml_remove.php?user_id=’

$mail = new SimpleMail();

$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 :

$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.’);

}

Trang 12

$query = ‘SELECT first_name, email FROM ml_users WHERE user_id = ‘

$query = ‘SELECT listname FROM ml_lists WHERE ml_id = ‘ $ml_id;

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

echo ‘ < h1 > Thank You ‘ $first_name ‘ < /h1 >

‘ mailing list ‘

‘has been sent to ‘ $email ‘ < /p >

} else {

echo ‘ < h1 > Thank You ‘ $first_name ‘ < /h1 >

Trang 13

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

Trang 14

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

Trang 15

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:

ml_users WHERE

$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

Ngày đăng: 03/07/2014, 07:20