WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Managing a Simple Mailing List
Categories : PHP, MySQL, Email Picture not available
Meloni Julie
Date : 2000-04-21
Grade : 0 of 5 (graded 0 times)
Viewed : 12722
Search : More Articles by Meloni Julie
Action : Grade This Article
Tools : My Favotite Articles


  Submit your own code examples 
 


A reader recently asked how I handle the subscribe/unsubscribe mechanism for the thickbook newsletter, and how that ties in with actually sending a message to all the recipients of the mailing list. It's a good question, and an easy enough thing to do, but first let me stress that this isn't any tricky thing I made up because I'm super cool -- if anything, I use this method only because I'm lazy. See, there's a ton of mailing list software out there that one can install on a system, and there are other, more cohesive sets of scripts that you can get to do the same thing. But, like I said, I was lazy one day and didn't want to download and install anything, so I made a couple of really simple pages that did what I needed them to do. Hopefully, someone will learn something from them.



First, there's the subscribe/unsubscribe script, and all it does is add or delete records from a database table. Call it "manage.phtml" or something like that. Required on the backend is a database of some sort, on which a "subscribers" table can be created. Majority rules in a democracy, so I'll use MySQL as the example database. You can use whatever database you normally use, just substitute the correct database connectivity functions from the PHP manual.



In my subscribers table, I use two fields: email_addr and date_added. You can have as many fields as you want, or can delete the date_added field. In this example, I'm just going to show you what I do, and you can modify as appropriate. In my subscribers table, the email_addr field is the unique field, meaning that you can't add another record that has exactly the same e-mail address. This alleviates duplicate subscriptions, and also makes it a simple and reliable method for deleting records when users want to unsubscribe.



So, let's create the subscribe/unsubscribe form (manage.phtml or whatever you want to call it). I use the same file for both subscribing and unsubscribing, as well as the form action itself, so this may get a little complicated. I'll go from top to bottom, then put all the pieces together in the form of a long chunk of code. Hang in there, though -- it's not all that painful.





At the top of the script, open the database connection and prepare the date stamp. Getting this out of the way at the beginning always alleviates a little stress for me.


// connect to db
$db = mysql_connect("servername", "username", "password")
or die ("Couldn't connect.");

mysql_select_db("yourDB", $db) or die ("Couldn't select db.");

// get a date stamp
$add_date = date("Y-m-d");


The next step is to figure out just which action needs to be performed, since this script is used for essentially four different functions: show the form, or subscribe, or unsubscribe, or print a response to an action. I use a variable called "op" to determine which OPeration (get it? "op"?) to perform. The value of this variable is set in a hidden form field.



The value of $op that we're looking for is "ds". This isn't some complicated programming abbreviation -- I made it up, and it stands for "do something". So, the first thing the script should do is look for the value of $op that equals "ds". This value will ONLY have been sent if the form has been submitted already. So, if the value of $op is not "ds", then the user hasn't seen the form and thus it should be shown:


if ($op != "ds") {

//they need to subscribe or unsubscribe

$text_block = "

<form name=\"form\" method=post action=\"$PHP_SELF\">
<input type=hidden name=op value=ds>

<p><strong>your e-mail address:&lt;/strong><br>
<input type=text name=\"email\" size=25>&lt;/p>

<p><strong>action:&lt;/strong><br>
<input type=radio name=\"action\" value=\"sub\" checked> sub
<input type=radio name=\"action\" value=\"unsub\"> unsub&lt;/p>

<P><input type=submit name=\"submit\" value=\"do it\">&lt;/p>
&lt;/form>

";

}


You'll notice that I've put the text inside a variable called $text_block. By putting the text in a variable, all I then have to do later in the script is echo the value of the variable $text_block, inside the master HTML template. It's a personal choice, and you can echo your text whenever or however you like.



The action of this form is $PHP_SELF, which means, as you can imagine, that it will reload itself as the submit button is pressed. Then, you'll see that this form has three fields: one hidden field, giving a value of "ds" to $op, one text field, called "email", where the user will place his or her email address, and finally a radio button set called "action", from which the user will decide which action (subscribe or unsubscribe) should be performed.



After the form is submitted, $op will equal "ds", and the value of $action will contain either "sub" or "unsub". So, we continue the if... statement from above, since upon submission, it will be skipped ($op == "ds"). The next else if... statement is executed if the value of $op is "ds" AND the value of $action is "sub" (subscribe). This code checks that the e-mail doesn't already reside in the subscribers table, then inserts it if it does not and prints a response, regardless.


else if (($op == "ds") && ($action == "sub")) {

// check they're not already subscribed,
// then subscribe them or return message

$check = "select email_addr from subscribers
where email_addr = \"$email\"";

$check_result = mysql_query($check)
or die("Can't execute check e-mail address.");

$check_num = mysql_num_rows($check_result);


if ($check_num == 0) {

// if $check_num is 0, then no match was found,
// and the user should be subscribed

$sql = "insert into subscribers
values(\"$email\", \"$add_date\")";

@mysql_query($sql) or die ("Couldn't insert email.");

$text_block = "
<P>Thanks for signing up!&lt;/p>
";

} else {

// if $check_num is not 0, then the user is
// already subscribed, and you should let
// them know it.

$text_block = "
<P>You're already subscribed!&lt;/p>
";

}

}


One more step: what to do if the value of $action is "unsub" (unsubscribe) instead of "sub". Well, it's just as simple as above, so extend the else if... statement for one more block, which will check that the e-mail is in the subscribers table before removing it, then removes it and prints a response, regardless.


else if (($op == "ds") && ($action == "unsub")) {

// check they're already subscribed,
// then unsubscribe them or return message

$check = "select email_addr from subscribers
where email_addr = \"$email\"";

$check_result = mysql_query($check)
or die("Can't execute check e-mail address.");

$check_num = mysql_num_rows($check_result);

if ($check_num == 0) {

// if $check_num is 0, then no match was found,
// and the user cannot be unsubscribed

$text_block = "
<P>Couldn't find your e-mail on the list!&lt;/p>
<P>You haven't been unsubscribed, because the
e-mail you entered is not in the database.";

} else {

// if $check_num is not 0, then the user is
// on the list, so can be unsubscribed.

$sql = "delete from subscribers
where email_addr = \"$email\"";

@mysql_query($sql) or die ("Couldn't delete email.");

$text_block = "
<P>You're unsubscribed!&lt;/p>
";
}

}

?>


Now that all the hard work is done, just echo the $text_block variable within a chunk of HTML:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>Subscribe/Unsubscribe&lt;/TITLE>
&lt;/HEAD>

<BODY>

<h1>Subscribe/Unsubscribe&lt;/h1>

<?php echo "$text_block"; ?>

&lt;/BODY>
&lt;/HTML>


From top to bottom, the "manage.phtml" script should look something like this:


<?

// connect to db
$db = mysql_connect("servername", "username", "password")
or die (
"Couldn't connect.");

mysql_select_db("yourDB", $db) or die ("Couldn't select db.");

// get a date stamp
$add_date = date("Y-m-d");


if (
$op != "ds") {

//they need to subscribe or unsubscribe

$text_block = "

<form name=\"form\" method=post action=\"$PHP_SELF\">
<input type=hidden name=op value=ds>

<p><strong>your e-mail address:&lt;/strong><br>
<input type=text name=\"email\" size=25>&lt;/p>

<p><strong>action:&lt;/strong><br>
<input type=radio name=\"action\" value=\"sub\" checked> sub
<input type=radio name=\"action\" value=\"unsub\"> unsub&lt;/p>

<P><input type=submit name=\"submit\" value=\"do it\">&lt;/p>
&lt;/form>

"
;

} else if ((
$op == "ds") && ($action == "sub")) {

// check they're not already subscribed,
// then subscribe them or return message

$check = "select email_addr from subscribers
where email_addr = \"$email\""
;

$check_result = mysql_query($check)
or die(
"Can't execute check e-mail address.");

$check_num = mysql_num_rows($check_result);


if (
$check_num == 0) {

// if $check_num is 0, then no match was found,
// and the user should be subscribed

$sql = "insert into subscribers
values(\"$email\", \"$add_date\")"
;

@
mysql_query($sql) or die ("Couldn't insert email.");

$text_block = "
<P>Thanks for signing up!&lt;/p>
"
;

} else {

// if $check_num is not 0, then the user is
// already subscribed, and you should let
// them know it.

$text_block = "
<P>You're already subscribed!&lt;/p>
"
;

}

} else if ((
$op == "ds") && ($action == "unsub")) {

// check they're already subscribed,
// then unsubscribe them or return message

$check = "select email_addr from subscribers
where email_addr = \"$email\""
;

$check_result = mysql_query($check)
or die(
"Can't execute check e-mail address.");

$check_num = mysql_num_rows($check_result);

if (
$check_num == 0) {

// if $check_num is 0, then no match was found,
// and the user cannot be unsubscribed

$text_block = "
<P>Couldn't find your e-mail on the list!&lt;/p>
<P>You haven't been unsubscribed, because the
e-mail you entered is not in the database."
;

} else {

// if $check_num is not 0, then the user is
// on the list, so can be unsubscribed.

$sql = "delete from subscribers
where email_addr = \"$email\""
;

@
mysql_query($sql) or die ("Couldn't delete email.");

$text_block = "
<P>You're unsubscribed!&lt;/p>
"
;
}

}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>Subscribe/Unsubscribe&lt;/TITLE>
&lt;/HEAD>

<BODY>

<h1>Subscribe/Unsubscribe&lt;/h1>

<?php echo "$text_block"; ?>

&lt;/BODY>
&lt;/HTML>





Now that you have the subscribe/unsubscribe mechanism in place, I'll show you how I send a newsletter out, using just a simple little form and a mail script. ("while" loops are your friends!). First, just the simple form...call it "send_mail.html". The form action should be something like "do_send_mail.phtml", and the only fields I use are a text field for "subject" and a textarea for "newsletter". You can use as many form fields as you'd like, as long as you modify the form and script appropriately.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>Send a Newsletter&lt;/TITLE>
&lt;/HEAD>

<BODY>

<h1>Send a Newsletter&lt;/h1>

<FORM ACTION="do_send_mail.phtml" METHOD="post">

<P><strong>Give it a subject:&lt;/strong><br>
<input type="text" name="subject" size=30>&lt;/p>

<P><strong>Newsletter body:&lt;/strong><br>
<textarea name="newsletter" cols=40 rows=30 wrap=virtual>&lt;/textarea>

<p><input type="submit" name="submit" value="Send Newsletter">&lt;/p>

&lt;/form>

&lt;/BODY>
&lt;/HTML>


The last little bit is the action of the form, the script called "do_send_mail.phtml". This script first looks for a value of $subject and $newsletter, and redirects back to the form if either of those values are empty:


if (($subject =="") || ($newsletter == "")) {

header("Location: http://www.yourdomain.com/send_mail.phtml");
exit;

}


Next, connect to the database and grab the e-mail addresses in the subscribers table:


// connect to db
$db = mysql_connect("servername", "username", "password")
or die ("Couldn't connect.");

mysql_select_db("yourDB", $db) or die ("Couldn't select db.");

$sql = "select email_addr from subscribers";

$res = mysql_query($sql) or die("Couldn't get addresses.");


Before launching into the loop that will send a mail message, set up the additional mail headers. In this case, I just use a "From:" line:


$headers = "From: \"Your Mailing List\" <you@yourdomain.com>\n";


Now for the loop that sends the mail. First, use the mysql_fetch_array function (or similar function for your database type) to get each record as an array. It makes more sense if there's more than one field that you're grabbing, but I use it anyway because it's fast. The following statement steps through the result set and sends the e-mail using the mail() function, to each e-mail address on the list:


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

$email_addr = $row[0];

mail("$email_addr", "$subject", $newsletter, $headers);

}


The value of $subject and $newsletter are what was entered in the previous form. Add an echo statement at the end of the script, so you know that it's finished, and that's all there is to it! The entire "do_send_mail.phtml" script looks something like this:


<?

if (($subject =="") || ($newsletter == "")) {

header("Location: http://www.yourdomain.com/send_mail.phtml");
exit;

} else {

// connect to db
$db = mysql_connect("servername", "username", "password")
or die (
"Couldn't connect.");

mysql_select_db("yourDB", $db) or die ("Couldn't select db.");

$sql = "select email_addr from subscribers";

$res = mysql_query($sql) or die("Couldn't get addresses.");

$headers = "From: \"Your Mailing List\" <you@yourdomain.com>\n";


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

$email_addr = $row[0];

mail("$email_addr", "$subject", $newsletter, $headers);

}

echo
"newsletter sent!";
}


?>








Saving Images in MySQL
Categories : MySQL, PHP, Graphics, Databases
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
Custom MySQL-functions
Categories : Databases, MySQL, PHP, PHP Functions
Referer Statistics
Categories : PHP, MySQL, HTTP, Databases
User identification using cookies in PHP and MySQL
Categories : PHP, Databases, MySQL, Cookies
Multicolumn Output from a Database with PHP
Categories : PHP, Databases, HTML and PHP, MySQL
Building a WAP site using PHP3 and MySQL
Categories : PHP, MySQL, WML, WAP
Creating an IE-Only Database Driven Menu System With PHP, MySQL and DHTML
Categories : PHP, MySQL, Databases, DHTML
Practical Date and Time examples with PHP and MySQL
Categories : Databases, MySQL, PHP, Date/time
PHP and MySQL News with Comments
Categories : PHP, Databases, MySQL
Sending Form Data in EMail
Categories : PHP, Email, HTML and PHP
Time Is Money Part 1 of 2 - Designing and implementing a Web-based application
Categories : PHP, Databases, MySQL, Complete Programs
tracking where and what on your site people are clicking
Categories : PHP, MySQL, HTML and PHP, HTML
Descriptions of Common Data Types
Categories : MySQL, Databases, PHP, PHP options/info, General
PHP, MySQL and Authentication 101
Categories : PHP, Databases, MySQL, Authentication
Anonymous wrote : 56
Help!! I can`t get this thing to work!
Miguel Leighton wrote : 304
Does anybody knows how to send a newsletter with
html?
Does anyone knows how to personalize the text, i.e.:
Dear Tom:

Thanks in advance.