Address Book Add New Contact
- Address Book Sort Contacts By Name
- Address Book Sort Contacts By Type
- Address Book Add New Contact
- Address Book Edit a Contact
- Address Book Delete a Contact
- Address Book Security
This page is a tutorial on an app page that you use to add a new contact to your address book. You will be entering data on 23 different fields. To be able to save, make sure you enter an email address into both email address fields. But if you know only one, enter it twice. If you know none, enter a@a.com or something equally harmless but do try to obtain an email address or two on this contact. The data will save if you enter nothing else but the 2 emails, but what's the point of not taking the task seriously. It's YOUR address book!
Here are the field choices (both email addresses are required fields, but if you need to fake it, z@z.com is fine):
- id
- First
- Middle
- Last
- Address1
- Address2
- City
- State
- Zip
- Email1
- Email2
- CelPhone
- WorkPhone
- HomePhone
- Fax
- RelationshipType
- RelationshipSpecific
- AssistantAssociate
- ReferredBy
- Website
- Blog
- Notes
- Friend
- Acquaintance
- Professional
- Client
- Group Member
- Business Associate
Let's look at the script. First, the JavaScript: The textCounter() function is for the textarea box input in the form which allows input of up to 400 characters in the Notes field. This function not only shows a counter of the number of characters which you have left out of 400. Once you hit 0, the textarea box prevents entering any more characters. This is like the maxlength attribute for regular text input tags. This attribute cannot apply to textarea boxes—it doesn't work. So this function is a way to make up for this problem.
Then comes the email validator—still JavaScript. Note that there can be a lot of stuff in a legitimate email, but even though we were liberal on construction, we were a stickler for which characters are in it. Bad email addresses will be caught and you will be asked to fix them before you can save. (So fun@notfun is no good, nor is silly@sillier.silliest, and don't even get us started on discussing sticker@dollar$sign.rich). Note the document.form1.Email1.focus() and document.form1.Email2.focus() codes. These force the cursor back to an email address field in which a bad entry is discovered, since the code says "in the form form1 and the input box Email1 (or Email2) we will now go use the focus() function to stick the cursor there."
On to the PHP codes: After getting ready to access the MySQL database by using the include with config.php in it, we define several form input filtering functions. The filteritless() function is used to filter the Notes field only, since who knows what one might put there? The filterit() function is used to filter most of the 23 fields, like names, addresses, phone numbers, etc. The url() function is used to filter Website, Blog, Facebook, and Twitter fields, and the email() function is used to filter Email1 and Email2 fields. In the email() function, the PHP function preg_match() is used with a regular expression and a standard email pattern. If a bad email is found, you are forced to start over with the input. Happily, the email validator in the JavaScript function has already been run on the email due to the onsubmit() event in the form, so the email has already been cleaned and the PHP email() function finding a naughty means someone's trying to pull a fasty by turning off JavaScript while entering data. For shame! The PHP preg_replace() function is used in the other three functions to simply dump any unacceptable character. Note that in all these PHP functions, the mysql_real_escape_string() function is used on all data before inserting it into the MySQL database table for security reasons.
Now the addressbook table is created if it does not exist already. It contains the 23 data fields you'll need in such a contact resource plus the omnipresent id field. This auto-incrementing primary field is used to reference a record—which is also a row, a contact, an address, etc. These start out in order in the db, but once you start doing any record deleting and then record adding, the "holes" left from the deletions quickly fill up with higher numbered ids and the ids no longer are in order. And id order, as you may know, is absolutely irrelevant. What's important is that MySQL uses this "primary field" to effectively access records. It needs a primary field and will give an error if you try to make a table without one, although it need not be called id. Feel free to add or substract fields here, but make sure to make the other needed changes in the rest of this code plus in the other four address book apps if you want things to work right.
The next section runs only if you have entered something into the First or Last name fields. Otherwise, the flow drops down to the form itself for data entry. If at least one of these fields is no longer a virgin, all 23 fields are validated and sanitized prior to insertion in the MySQL db. We've already discussed what function filters what data, but one field, RelationshipType, gets no filtering, because it can only have one of the form's option values from its select box dropdown—quite safe indeed.
Next there is a mysql_query() that uses the MySQL SELECT statement and WHERE clause to check the addressbook table for the First and Last names you are entering. If it finds them, you are restarted. Feel free to add AND Middle='$Middle' to avoid the issue of trying to enter Joe Q. Blow and Joe P. Blow both in this table. Anyway, you see the message "This name exists. Please try again." if you try to put someone in twice.
Now we use the INSERT INTO statement to load our MySQL database table with the record data just entered in the form. The id field just gets two single quotes to nudge it into auto-incrementing. You get a message if the saving was okay, and the page reloads to accept more input.
Finally, there is the form. It uses the onsubmit() event to trap bad emails, maxlength attributes to limit input, the textCounter() function to limit textarea box input, and there is a button that allows you to quit and return to the home page, which is: Address Book Sort Contacts By Name.
On to the code for the script. Name the following: address-book-add.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>PHP Address Book — Add Contact</TITLE>
<meta name="description" content="PHP Address Book — Add Contact">
<meta name="keywords" content="PHP Address Book,PHP Address Book - Add Contact,Content Management System,cms,javascript, dhtml, DHTML">
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;}
p, li, td {font:13px Verdana; color:black;}
h1 {font:bold 28px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
h3 {font:bold 15px Verdana;}
.address {position:absolute; left:50px; top:70px; width:900px; margin:0; padding:10px; background-color:#cccccc; border:2px solid #000; font:bold 11px Verdana;}
.r (text-align:right;}
.l (text-align:left;}
.c (text-align:center;}
</style>
<SCRIPT LANGUAGE="JavaScript">
<!--
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit){field.value = field.value.substring(0, maxlimit);}
else{countfield.value = maxlimit - field.value.length;}}
function email(){
var ck_email = /^[A-Za-z0-9-_]+(\.[A-Za-z0-9-_]+)*@([A-Za-z0-9-_]+\.)?([A-Za-z0-9-_]+(\.[A-Za-z]{2,6})(\.[A-Za-z]{2})?)$/;
if (document.form1.Email1.value.search(ck_email)==-1)
{alert("That email address is not valid. Try again.");document.form1.Email1.focus();return false;}
if (document.form1.Email2.value.search(ck_email)==-1)
{alert("That email address is not valid. Try again.");document.form1.Email2.focus();return false;}
return true;}
// -->
</script>
</head>
<body>
<?php
include_once"../config.php";
function filteritless(){
global $S;
$S=strip_tags($S);
$pattern = '/[^a-zA-Z0-9\\s\\.\\,\\!\\;\\-\\_\\"\\?\\047\\:\\(\\)\\&\\#\\=\\@\\/\\%]/i';
$replacement = '';
$S=preg_replace($pattern, $replacement, $S);
$S=mysql_real_escape_string($S);}
function filterit(){
global $S;
$S=strip_tags($S);
$pattern = '/[^a-zA-Z0-9\\s\\.\\,\\-\\_\\(\\)\\#\\047]/i';
$replacement = '';
$S=preg_replace($pattern, $replacement, $S);
$S=mysql_real_escape_string($S);}
function email(){
global $S;
$S = strip_tags($S);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$S)) {
echo '<script language="javascript">alert("That email address is not valid."); window.location = "address-book-add.php"; </script>';}
$S=mysql_real_escape_string($S);}
function url(){
global $S;
$S = strip_tags($S);
$pattern = '/[^a-zA-Z0-9\\.\\,\\!\\;\\-\\_\\*\\@\\=\\+\\$\\/\\&\\[\\]\\#\\?\\047\\:\\(\\)]/i';
$replacement = '';
$S=preg_replace($pattern, $replacement, $S);
$S=mysql_real_escape_string($S);}
$sql = "CREATE TABLE IF NOT EXISTS addressbook (
id int(4) NOT NULL auto_increment,
First varchar(20) NOT NULL,
Middle varchar(20) NOT NULL,
Last varchar(20) NOT NULL,
Address1 varchar(40) NOT NULL,
Address2 varchar(40) NOT NULL,
City varchar(40) NOT NULL,
State varchar(10) NOT NULL,
Zip varchar(10) NOT NULL,
Email1 varchar(90) NOT NULL,
Email2 varchar(90) NOT NULL,
CelPhone varchar(20) NOT NULL,
WorkPhone varchar(20) NOT NULL,
HomePhone varchar(20) NOT NULL,
Fax varchar(20) NOT NULL,
RelationshipType varchar(20) NOT NULL,
RelationshipSpecific varchar(90) NOT NULL,
AssistantAssociate varchar(40) NOT NULL,
ReferredBy varchar(40) NOT NULL,
Website varchar(90) NOT NULL,
Blog varchar(90) NOT NULL,
Facebook varchar(90) NOT NULL,
Twitter varchar(90) NOT NULL,
Notes varchar(400) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
if(isset($_POST['First']) || isset($_POST['Last'])){
$First = $_POST['First'];$S=$First;filterit();$First=$S;
$Middle = $_POST['Middle'];$S=$Middle;filterit();$Middle=$S;
$Last = $_POST['Last'];$S=$Last;filterit();$Last=$S;
$Address1 = $_POST['Address1'];$S=$Address1;filterit();$Address1=$S;
$Address2 = $_POST['Address2'];$S=$Address2;filterit();$Address2=$S;
$City = $_POST['City'];$S=$City;filterit();$City=$S;
$State = $_POST['State'];$S=$State;filterit();$State=$S;
$Zip = $_POST['Zip'];$S=$Zip;filterit();$Zip=$S;
$Email1 = $_POST['Email1'];$S=$Email1;email();$Email1=$S;
$Email2 = $_POST['Email2'];$S=$Email2;email();$Email2=$S;
$CelPhone = $_POST['CelPhone'];$S=$CelPhone;filterit();$CelPhone=$S;
$WorkPhone = $_POST['WorkPhone'];$S=$WorkPhone;filterit();$WorkPhone=$S;
$HomePhone = $_POST['HomePhone'];$S=$HomePhone;filterit();$HomePhone=$S;
$Fax = $_POST['Fax'];$S=$Fax;filterit();$Fax=$S;
$RelationshipType = $_POST['RelationshipType'];
$RelationshipSpecific = $_POST['RelationshipSpecific'];$S=$RelationshipSpecific;filterit();$RelationshipSpecific=$S;
$AssistantAssociate = $_POST['AssistantAssociate'];$S=$AssistantAssociate;filterit();$AssistantAssociate=$S;
$ReferredBy = $_POST['ReferredBy'];$S=$ReferredBy;filterit();$ReferredBy=$S;
$Website = $_POST['Website'];$S=$Website;url();$Website=$S;
$Blog = $_POST['Blog'];$S=$Blog;url();$Blog=$S;
$Facebook = $_POST['Facebook'];$S=$Facebook;url();$Facebook=$S;
$Twitter = $_POST['Twitter'];$S=$Twitter;url();$Twitter=$S;
$Notes = $_POST['Notes'];$S=$Notes;filteritless();$Notes=$S;
$check_user_data = mysql_query("SELECT First FROM addressbook WHERE First='$First' AND Last='$Last'") or die(mysql_error());
if(mysql_num_rows($check_user_data) >0)
{echo '<script language="javascript">alert("This name exists. Please try again.")</script>;';
unset($First);unset($Last);
}else{
mysql_query("INSERT INTO addressbook (id, First, Middle, Last, Address1, Address2, City, State, Zip, Email1, Email2, CelPhone, WorkPhone, HomePhone, Fax, RelationshipType, RelationshipSpecific, AssistantAssociate, ReferredBy, Website, Blog, Facebook, Twitter, Notes)
VALUES ('', '$First', '$Middle', '$Last', '$Address1', '$Address2', '$City', '$State', '$Zip', '$Email1', '$Email2', '$CelPhone', '$WorkPhone', '$HomePhone', '$Fax', '$RelationshipType', '$RelationshipSpecific', '$AssistantAssociate', '$ReferredBy', '$Website', '$Blog', '$Facebook', '$Twitter', '$Notes')") or die('Error ,saving failed');
$rc = mysql_affected_rows();
if ($rc>0){unset($First);unset($Last);
echo '<script language="javascript">alert("The saving was successfully accomplished.");window.location = "address-book-sort-by-name.php"; </script>';}
else{echo '<script language="javascript">alert("The saving was unsuccessful.");</script>';}
}}
mysql_close();
?>
<center><h1>PHP Address Book — Add Contact</h1></center>
<div class="address"><form name="form1" action="address-book-add.php" method="post" onsubmit="return email()">
<table>
<tr><td class='r' align=right>First Name:</td><td class='l'>
<input type="text" name="First" maxlength="20" size="20">
<td class='r' align=right>Middle Name:</td><td>
<input type="text" name="Middle" maxlength="20" size="20">
<td class='r' align=right>Last Name:</td><td>
<input type="text" name="Last" maxlength="20" size="20"></td></tr>
<tr><td class='r' align=right>Address 1:</td><td colspan="5" class='l'>
<input type="text" name="Address1" maxlength="40" size="40"></td></tr>
<tr><td class='r' align=right>Address 2:</td><td colspan="5" class='l'>
<input type="text" name="Address2" maxlength="40" size="40"></td></tr>
<tr><td class='r' align=right>City:</td><td colspan="5" class='l'>
<input type="text" name="City" maxlength="40" size="40"></td></tr>
<tr><td class='r' align=right>State:</td><td colspan="5" class='l'>
<input type="text" name="State" maxlength="10" size="10"></td></tr>
<tr><td class='r' align=right>Zip:</td><td colspan="5" class='l'>
<input type="text" name="Zip" maxlength="10" size="10"></td></tr>
<tr><td class='r' align=right>Email 1:</td><td colspan="5" class='l'>
<input type="text" name="Email1" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Email 2:</td><td colspan="5" class='l'>
<input type="text" name="Email2" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Cel Phone:</td><td colspan="5" class='l'>
<input type="text" name="CelPhone" maxlength="20" size="20"></td></tr>
<tr><td class='r' align=right>Work Phone:</td><td colspan="5" class='l'>
<input type="text" name="WorkPhone" maxlength="20" size="20"></td></tr>
<tr><td class='r' align=right>Home Phone:</td><td colspan="5" class='l'>
<input type="text" name="HomePhone" maxlength="20" size="20"></td></tr>
<tr><td class='r' align=right>Fax:</td><td colspan="5" class='l'>
<input type="text" name="Fax" maxlength="20" size="20"></td></tr>
<tr><td class='r' align=right>Relationship Type:</td><td colspan="5" class='l'>
<select name="RelationshipType">
<option value="Friend">Friend
<option value="Acquaintance">Acquaintance
<option value="Professional">Professional
<option value="Client">Client
<option value="Group Member">Group Member
<option value="Business Associate">Business Associate
</select>
</td></tr>
<tr><td class='r' align=right>Relationship Specific:</td><td colspan="5" class='l'>
<input type="text" name="RelationshipSpecific" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Assistant/Associate:</td><td colspan="5" class='l'>
<input type="text" name="AssistantAssociate" maxlength="40" size="40"></td></tr>
<tr><td class='r' align=right>Referred By:</td><td colspan="5" class='l'>
<input type="text" name="ReferredBy" maxlength="40" size="40"></td></tr>
<tr><td class='r' align=right>Website:</td><td colspan="5" class='l'>
<input type="text" name="Website" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Blog:</td><td colspan="5" class='l'>
<input type="text" name="Blog" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Facebook:</td><td colspan="5" class='l'>
<input type="text" name="Facebook" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Twitter:</td><td colspan="5" class='l'>
<input type="text" name="Twitter" maxlength="90" size="90"></td></tr>
<tr><td class='r' align=right>Notes:</td><td colspan="5" class='l'>
<textarea name="Notes" id='Notes' cols="80" rows="5" onKeyDown="textCounter(this.form.Notes,this.form.remLen,400)" onKeyUp="textCounter(this.form.Notes,this.form.remLen,400)"></textarea><input readonly type='text' name='remLen' size='3' maxlength='3' value="400"></td></tr>
<tr><td colspan="2"> </td><td colspan="2"><input name="Submit" type="submit" value="Add Contact"> <button type="button" onclick="javascript:window.location='address-book-sort-by-name.php'">Home</button></td><td colspan="2"> </td></tr>
</table></form></div>
</body>
</html>