Simple PHP web based address book using MySql

82
rate or flag this page
Facebook

By Alpho011

Screen shot of application

Using the $_GET variable to do the work.

Today we will be creating a web based address book using PHP and MySql, it will be using the $_GET superglobal, as a means of reviewing the database contents.

Before we start here are the source files:

http://diadde.com/dl/addressBook.zip

Working demo:

http://diadde.com/test/addressTest.php

First, create the data base using this sql snippet:

CREATE TABLE IF NOT EXISTS `address` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(30) default NULL,
`phone` varchar(30) default NULL,
`email` varchar(30) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

Then insert some data into our database using this snippet:

INSERT INTO `address` (`id`, `name`, `phone`, `email`) VALUES
(1, 'Laika Clay', '430-555-2252', 'laika@doggie.com'),
(2, 'Tiger Clay', '658-555-5985', 'tiger@kittie.us'),
(4, 'A Clay', '555-777-0000', 'clay@php.com'),
(5, 'Santa Clause', '888-888-7777', 'santa@np.net');

Now that we have that in place, we can create the form that be used for adding and editing the entry:

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=added" method="post">
<table class="tableStyleClassTwo">
<tr><td>Name:</td><td><div align="left">
<input type="text" name="name" />
</div></td></tr>
<tr><td>Phone:</td><td><div align="left">
<input type="text" name="phone" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" name="email" />
</div></td></tr>
<tr><td colspan="2" align="center"><a href="javascript:history.go(-1);">Back</a> | <input name="Submit" type="submit" id="Submit" value="Add New Contact" <?php if($disable ==1){?>disabled<?php } ?>/></td></tr>
<input type="hidden" name="mode" value="added">
</table>

Simple enough, we will use this form in our all in one page address book, it will be used in adding and editing the database contents (addresses).

First thing we want to do is to setup the variable that will be used to run this thing:

$mode = $_GET['mode'];

The above will be called throughout the app to control the functions of it.

Before we can use the $mode var we setup a switch, this will be used in different sections of the app to do the actions:

switch($mode){

//cases in bewteen

}

If you are used to using ASP or Vb Script switch is the same as select case.

The cases are as follows:

  • add
  • added
  • edit
  • edited
  • remove

ADD:

This Case will add new contacts to our database, and is called by a hyperlink which will use the word 'add', look in the address bar after you click this, and will see this after the ? mark.

case 'add':
?>
<h2>Add Contact</h2>
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=added" method="post">
<table class="tableStyleClassTwo">
<tr><td>Name:</td><td><div align="left">
<input type="text" name="name" />
</div></td></tr>
<tr><td>Phone:</td><td><div align="left">
<input type="text" name="phone" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" name="email" />
</div></td></tr>
<tr><td colspan="2" align="center"><a href="javascript:history.go(-1);">Back</a> | <input name="Submit" type="submit" id="Submit" value="Add New Contact" <?php if($disable ==1){?>disabled<?php } ?>/></td></tr>
<input type="hidden" name="mode" value="added">
</table>
</form>
<?php
break;

ADDED:

This will called the case added, but unlike add it will use the querystring (address bar) to function and then redirect the page after we are done with adding the contact.

//added a record
case 'added':
//first setup the vars
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
//then lets use'em
$sql = "INSERT INTO address (name, phone, email) VALUES ('" . $name . "','" . $phone . "','" . $email . "')";
//echo $sql;
//return;
mysql_query($sql);
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

EDIT:

Calls the address using the address bar vars with name , email , phone number , but moore importantly the id of the record. We need this to perform the edit on that record, we have to be specific on the updating of the records, other wise we could update all the records with same information (no go)

?>
<h2>Editing: <?=$_GET['name'];?></h2>
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=edited" method="post">
<table width="399" class="tableStyleClassTwo">
<tr><td width="87">Name:</td>
<td width="551"><div align="left">
<input type="text" value="<?=$_GET['name'];?>" name="name" />
</div></td></tr>
<tr><td>Phone:</td><td><div align="left">
<input type="text" value="<?=$_GET['phone'];?>" name="phone" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" value="<?=$_GET['email'];?>" name="email" />
</div></td></tr>
<tr><td colspan="2" align="center"><a href="javascript:history.go(-1);">Back</a> |<input name="Submit" type="submit" value="Save Changes" /></td></tr>
<input type="hidden" name="mode" value="edited">
<input type="hidden" name="id" value="<?=$_GET['id'];?>">
</table>
</form>
<?php
break;

EDITED:

This uses the id we planted inside of the form, in a text field named id, to show this click on a record to edit, look at the code source, (view source), you shold see an input named "id". That was used in the update sql to update that record ONLY.

case 'edited':
//again clarify the vars
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$id = $_POST['id'];
//do the query
$sql = "UPDATE address SET name = '" . $name ."', phone = '" . $phone . "', email = '" . $email . "' WHERE id = '" . $id . "'";
mysql_query($sql);
//echo $sql;
//return;
//below you can either redirect show a message or put a link, and if you think harder you can probably do alot more
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

REMOVE:

Does what is says deletes the record, once and for all, there is no coming back after this.

case 'remove':
$id = $_GET['id'];
//lets remove the record this one is easy
$sql ="delete from address where id= '" . $id ."'";
//run the query
mysql_query($sql);
//echo $sql;
//return;
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

DEFAULT:

//this will show the table scructure by default (ie, no actions)
default:
//opening query
$sql ="SELECT * FROM address ORDER BY name ASC";
$data = mysql_query($sql);
//you can put in an error statement if no records or just display, just do what makes sense to you, the rest will come
?>
<h2>Phone Book Example</h2>
<table class="tableStyleClass">
<tr>
<th width="100">Name</th>
<th width="100">Phone</th>
<th width="200">Email</th>
<th width="100" colspan="2">Admin</th>
</tr>
<td colspan="5" align="right"><?php if($disable!=1){?><div align="right"><a href="<?=$_SERVER['PHP_SELF'];?>?mode=add"?mode=add>Add Contact</a><?php }else{?>Contact Book is Full<?php } ?></div></td>
<?php
//lets set a variable for offest coloered rows
$rowColor = 0;
//here is the loop using the statement above
while($info = mysql_fetch_array( $data )){
if($rowColor==0){
?>
<tr class="oddClassStyle">
<?php
$rowColor =1;
}elseif($rowColor==1){
?>
<tr class="evenClassStyle">
<?php
$rowColor = 0;
}
?>
<td><?=$info['name'];?></td>
<td><?=$info['phone'];?></td>
<td><a href=mailto:"<?=$info['email'];?>"><?=$info['email'];?></a></td>
<td><a href="<?=$_SERVER['PHP_SELF'];?>?id=<?=$info['id'];?>&name=<?=$info['name'];?>&phone=<?=$info['phone'];?>&email=<?=$info['email'];?>&mode=edit" >Edit </a></td>
<td><a href="<?=$_SERVER['PHP_SELF'];?>?id=<?=$info['id'];?>&mode=remove">Remove</a></td>
</tr>
<?php
}
?>
</table>
<?php
break;

This is a special case that defaults and show what we want to display in case we are not trying to edit or add, etc.

The entire code follows:

<?php
ob_start();//this just buffers the header so that you dont recieve an error for returning to the same page
if(isset($_GET['id']) && $_GET['mode'] == 'edit'){
//lets get the details for the paage title
$title = "We are editing: " . $_GET['name'] . " are you sure!!!";
}
?>
<html>
<head>
<title><?php if(!$title){?>Address Book<?php }else{ echo $title; }//end if?></title>
<style>
body{font-family:Arial, Helvetica, sans-serif;font-size:10px;}
table.tableStyleClass{border-collapse:collapse;border:1px solid #cccccc;background-color:#f1f1f1;width:650px;font-family:Arial, Helvetica, sans-serif;font-size:11px;}
table.tableStyleClassTwo{border-collapse:collapse;border:1px solid #cccccc;background-color:#f1f1f1;width:350px;font-family:Arial, Helvetica, sans-serif;font-size:11px;}
th{background-color:#999999;color:#ffffff;margin:1px;}
td{border-right:1px solid #cccccc;padding:2px;text-align:center;}
.oddClassStyle{background-color:#ffffff;border-bottom:1px solid #cccccc;}
.evenClassStyle{background-color:#f1f1f1;border-bottom:1px solid #cccccc;}
</style>
</head>
<body>

<?php
// Connects to your Database
mysql_connect("#", "#", "#") or die(mysql_error());
mysql_select_db("address") or die(mysql_error());
//we will use a case switch to look for the variable to make the decisions on what to show
//this is the variable that will control the switch case
//first lets set it looking for a query string or a post version of it
/*if(isset($_GET['id'])){
$mode = $_GET['mode'];//address bar version
$id = $_GET['id'];
}else{
$mode = $_POST['mode'];//form based version
$id = $_POST['id'];
}// now we know yay*/
//begin the switch
$mode = $_GET['mode'];
//look to see if the book is full
$checkSql="select count(id) as eCount from address";
$result = mysql_query($checkSql);
$row = mysql_fetch_assoc($result);
if($row['eCount'] == 6){
$disable = 1;
}
switch($mode){
//add a record
case 'add':
?>
<h2>Add Contact</h2>
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=added" method="post">
<table class="tableStyleClassTwo">
<tr><td>Name:</td><td><div align="left">
<input type="text" name="name" />
</div></td></tr>
<tr><td>Phone:</td><td><div align="left">
<input type="text" name="phone" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" name="email" />
</div></td></tr>
<tr><td colspan="2" align="center"><a href="javascript:history.go(-1);">Back</a> | <input name="Submit" type="submit" id="Submit" value="Add New Contact" <?php if($disable ==1){?>disabled<?php } ?>/></td></tr>
<input type="hidden" name="mode" value="added">
</table>
</form>
<?php
break;
//added a record
case 'added':
//first setup the vars
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
//then lets use'em
$sql = "INSERT INTO address (name, phone, email) VALUES ('" . $name . "','" . $phone . "','" . $email . "')";
//echo $sql;
//return;
mysql_query($sql);
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

case 'edit':
?>
<h2>Editing: <?=$_GET['name'];?></h2>
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=edited" method="post">
<table width="399" class="tableStyleClassTwo">
<tr><td width="87">Name:</td>
<td width="551"><div align="left">
<input type="text" value="<?=$_GET['name'];?>" name="name" />
</div></td></tr>
<tr><td>Phone:</td><td><div align="left">
<input type="text" value="<?=$_GET['phone'];?>" name="phone" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" value="<?=$_GET['email'];?>" name="email" />
</div></td></tr>
<tr><td colspan="2" align="center"><a href="javascript:history.go(-1);">Back</a> |<input name="Submit" type="submit" value="Save Changes" /></td></tr>
<input type="hidden" name="mode" value="edited">
<input type="hidden" name="id" value="<?=$_GET['id'];?>">
</table>
</form>
<?php
break;

case 'edited':
//again clarify the vars
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$id = $_POST['id'];
//do the query
$sql = "UPDATE address SET name = '" . $name ."', phone = '" . $phone . "', email = '" . $email . "' WHERE id = '" . $id . "'";
mysql_query($sql);
//echo $sql;
//return;
//below you can either redirect show a message or put a link, and if you think harder you can probably do alot more
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

case 'remove':
$id = $_GET['id'];
//lets remove the record this one is easy
$sql ="delete from address where id= '" . $id ."'";
//run the query
mysql_query($sql);
//echo $sql;
//return;
//done take me back to the main page
header('location: ' . $_SERVER['PHP_SELF']);
break;

//this will show the table scructure by default (ie, no actions)
default:
//opening query
$sql ="SELECT * FROM address ORDER BY name ASC";
$data = mysql_query($sql);
//you can put in an error statement if no records or just display, just do what makes sense to you, the rest will come
?>
<h2>Phone Book Example</h2>
<table class="tableStyleClass">
<tr>
<th width="100">Name</th>
<th width="100">Phone</th>
<th width="200">Email</th>
<th width="100" colspan="2">Admin</th>
</tr>
<td colspan="5" align="right"><?php if($disable!=1){?><div align="right"><a href="<?=$_SERVER['PHP_SELF'];?>?mode=add"?mode=add>Add Contact</a><?php }else{?>Contact Book is Full<?php } ?></div></td>
<?php
//lets set a variable for offest coloered rows
$rowColor = 0;
//here is the loop using the statement above
while($info = mysql_fetch_array( $data )){
if($rowColor==0){
?>
<tr class="oddClassStyle">
<?php
$rowColor =1;
}elseif($rowColor==1){
?>
<tr class="evenClassStyle">
<?php
$rowColor = 0;
}
?>
<td><?=$info['name'];?></td>
<td><?=$info['phone'];?></td>
<td><a href=mailto:"<?=$info['email'];?>"><?=$info['email'];?></a></td>
<td><a href="<?=$_SERVER['PHP_SELF'];?>?id=<?=$info['id'];?>&name=<?=$info['name'];?>&phone=<?=$info['phone'];?>&email=<?=$info['email'];?>&mode=edit" >Edit </a></td>
<td><a href="<?=$_SERVER['PHP_SELF'];?>?id=<?=$info['id'];?>&mode=remove">Remove</a></td>
</tr>
<?php
}
?>
</table>
<?php
break;

}//end the switch
?>
</body>
</html>
<?php ob_flush();?>

You may notice some other functions like ob_start(), etc that I have included in the tut, these I will be happy to explain if you have any comments or questions.

Recap: There are more elegant and secure ways to capture and display the data, but the point of the article is give new users something to build on and develop their own techniques and habits.

There are alot of features that could be used in this, we could archive the addresses, instead of deleting, use some nice images to redecorate the whole app, even incorporate this into something that could bulk imprt address, maybe some API, yahoo anyone, skies the limit. Anyway take it and run with it.

Once again thank you and ask if any questions or concerns.




PHP MySql Suggested Reading

Build Your Own Database Driven Website Using PHP and MySQL
Amazon Price: $12.94
List Price: $39.95

Comments

Lgali profile image

Lgali 2 years ago

thnaks for sharing this

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Welcome, once again use it if you need and be sure to pass it along.

Thank you,

pkoson profile image

pkoson 2 years ago

Simple PHP web based address book using MySql

Good point. I hope the rest of the Asteroidea class welcome me with five arms wide open

kevinritt 2 years ago

How can you add a warning before you delete a row. For example, click 'Remove' then a warning comes up asking 'Are you sure you want to delete this record? Then select: Yes -- No.

Is this possible?

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Hello kevinritt:

 

Yes it is, for example; you can use javascript to pop up a confirmation box, "Do you really want to delete this?"

ok or cancel

 

if one clicks ok, the location object (location.href) will have the querystring ready to point back at the page with the id:

function delMe(id){

var conBox = confirm("Do you really want to delete this?")

if(conBox == true){

location.href="whateverPage.php?id=" +id;

}else{

return;

}

Nir Cohen 2 years ago

Thanks! That would be handy.

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Hello Nir Cohen:

This will answer how to do that and is using the same files.

http://hubpages.com/hub/Show-Javascript-Confirmati

astray555 2 years ago

Great info I really will think about this. Thanks for sharing.

Conrad2010 2 years ago

Nice Job.

Just a note to everyone she uses short tags a lot, (i.e <?=code?>) which will be removed in PHP Version 6.0.

Again nice job.

Cheers

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Conrad2010 , thanks I didn't that, when will version 6 n out?

Conrad2010 2 years ago

Hey Alpho011

They keep changing the date it will be available.

I have include a link for you it is The Minutes PHP Developers Meeting this will give you all the changes that the developers are making to PHP 6

Here's the link.

http://www.php.net/~derick/meeting-notes.html

 

Cheers

psychicdog.net profile image

psychicdog.net Level 4 Commenter 2 years ago

I've just completed a matchmaking site using php/msql with user login and profiles but I wish I'd read your article a couple of months ago - very elegant solutions. Thanks AlphoO11. Heh also if I can ask: you wouldn't be interested in writing one on resizing uploaded user images to thumbnails? There seems to be a number of different options including GD library, Zend has a few and then there's just the plain img tag in html and constraining width and height.Would love to hear your advice on this.

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Conrad2010 thanks

Alpho011 profile image

Alpho011 Hub Author 2 years ago

psychicdog.net Yes I will write something that does thumbnails and stores the image name in the db

psychicdog.net profile image

psychicdog.net Level 4 Commenter 2 years ago

Alpho011, thanks so very much, I really appreciate it, especially since I've been raking thru php pages on the net for months and trually, your stuff stands out.

Craig 2 years ago

Really nice and simple.

I've been working on a Desktop Inventory program for work for the last few weeks. Basically just to learn php, css, mysql. I think I'm going to switch my gears a bit, and apply your tips for this Address book, to my Inventory program and cut out a few pages.

Thank you

Pravin 2 years ago

Play with php http://www.mahaphpcode.com

rajeshkumars 2 years ago

i got an error in line 146

this my coding

http://www.drivehq.com/file/df.aspx/publish/Udhaya

and my error screen

http://www.drivehq.com/file/df.aspx/publish/Udhaya

not working

when mouse over add contact button it show coding in status bar.. check in error screen

changed register_globals=on in wamp server php.ini file

; to possible security problems, if the code is not very well thought of.

register_globals = on

please make it fast someone help soon...

rajeshkumars 2 years ago

when trying to click on add contact it shows

Forbidden

You don't have permission to access /Others/< on this server.

rajeshkumars 2 years ago

echo $_SERVER['PHP_SELF'];

?>

">Add Contact (close anchor tag)

rajeshkumars 2 years ago

echo $_SERVER['PHP_SELF'];

?>

(open anchor tag) href=(double quotes)(lesser than & quesion mark)$_SERVER['PHP_SELF'];?>">Add Contact (close anchor tag)

echo works but anchor tag link not work

using wamp server version 2.0

Bellton 2 years ago

Awesome script. Congrats. Im using it at my company.

Question:

How can you add pagination to this script? "LIMIT" etc...

rajeshkumars 2 years ago

Please answer me

echo $_SERVER['PHP_SELF'];

?>

(open anchor tag) href=(double quotes)(lesser than & quesion mark)$_SERVER['PHP_SELF'];?>">Add Contact (close anchor tag)

echo works but anchor tag link not work

using wamp server version 2.0

actually i cant use, php tag get inside html

sorry cant post the less than symbol here

input type='text' value='?=$_GET['name'];?>' name='name'/>

rajeshkumars 2 years ago

ha ha ha,

at last i found the prob, should open the

short_open_tag = On

in php.ini file

magiwells 23 months ago

Thank you for the great script I used it to make a database for an online catalog. The administrator side is working great. I would like to make a customer side that would multiply the cost of product by one of the margins in the data base.

data base set up:

id|sku|description|cost|m1|m2|m3

I would like to display on the customer side:

sku|description|cost*m1 or m2 or m3

I can't figure out the math stuff in the display loop

any advise

beginner 21 months ago

I am not able to get the data from database.

If i a click on any of the link(edit,remove or add contact) i redirected to a new page, where i treated with below error:-

Access forbidden!

"New XAMPP security concept:

Access to the requested object is only available from the local network.

This setting can be configured in the file "httpd-xampp.conf"."

Alpho011 profile image

Alpho011 Hub Author 21 months ago

@beginner

give me some more info on your PHP, MySQL setup, that will help me help you.

Neil Henao Buitrago 21 months ago

Excelente aplicación, para usuarios principiantes muy bien explicado y además muy sencilla de usar. Mil gracias.

Excellent application for beginners very well explained and also very easy to use. Thank you

Alpho011 profile image

Alpho011 Hub Author 21 months ago

Glad you got something from it!

snkhan120 profile image

snkhan120 20 months ago

nice

kep n tuch

Alpho011 profile image

Alpho011 Hub Author 20 months ago

@snkhan120 will do

Bill Wiseman 20 months ago

If a # is placed in the data fields you can not call the data back to edit it. Why? Is there a fix?

Alpho011 profile image

Alpho011 Hub Author 20 months ago

@Bill Wiseman

It wasn't the "#" it was the slashes in the url, remember it is using $_GET to grab the record info to populate, this is not a production quality example, in real life you could stop that with some validation before POSTING to the insert script.

Either an expression or an array with symbols or characters not allowed that would re-show the form if not a valid character or symbol, you could also do it with Javascript, but if the user does have JS turned on, the same thing can happen, it is better to allow the server do the validation.

Hope that helps.

Sam 20 months ago

There should definitely be some database escaping going on here.

$name = $_POST['name'];

$phone = $_POST['phone'];

$email = $_POST['email'];

$id = $_POST['id'];

//do the query

$sql = "UPDATE address SET name = '" . $name ."', phone = '" . $phone . "', email = '" . $email . "' WHERE id = '" . $id . "'";

mysql_query($sql);

This is a no-no

$sql = sprintf( "UPDATE address SET name='%s', phone='%s', email='%s' WHERE id='%d'",

mysql_escape_string( $_POST['name'], $_POST['phone'], $_POST['email'], $_POST['id'] );

mysql_query($sql);

This is better.

This is a MAJOR security issue and should definitely be illustrated in your example.

leslie 20 months ago

hi,

thanks for very usefull script: at last a nice script.

kind regards: leslie

adorababy profile image

adorababy 19 months ago

Web-based address books are very useful for sharing contacts among multiple users in an office or making your addresses available no matter where you travel.

Tom O'Hare 19 months ago

Is is possible to retrieve this type of information from a flat file csv database, sql might be a step too far for me at this time.

Alpho011 profile image

Alpho011 Hub Author 19 months ago

@Tom O'Hare:

Yes it is, there is CSV tut under my name which should help you.

Rolips 19 months ago

i've got an error when trying to run this program using wampserver, this is the error:

Notice: Undefined variable: disable in C:\wamp\www\addressTest.php on line 150

how can i fix it

thanks

pneelam 19 months ago

amazing work

very nice code

thanks

Alpho011 profile image

Alpho011 Hub Author 19 months ago

@Rolips

take a look and make sure you are assigning a value to all of your variables, it could one or more are empty, or sometimes on new server configurations you have to clear or give a new var an empty value.

Rolips 18 months ago

thanks for the reply but what amazed me is when i tried same code with linux (ubuntu 9.04), it runs perfectly. I checked the code and now the error is this:

Notice: Undefined index: mode in C:\wamp\www\inventory.php on line 57

But this error will not appear in linux

thanks a lot

kelvin 17 months ago

thanks for this info!!!

chandu 15 months ago

thanks.

robin 12 months ago

Links are dead

pls geef me a link

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    • No HTML is allowed in comments, but URLs will be hyperlinked
    • Comments are not for promoting your Hubs or other sites

    working