4 Steps Simple Address Book With PHP MYSQL (Free Download!)

Welcome to a tutorial on how to create a simple address book with PHP and MYSQL. Want to create your own address book? Or just want a project to learn more about PHP MYSQL?

A simple PHP MYSQL address book has the following general components:

  1. Database table to store the address book entries.
  2. PHP library to manage the entries.
  3. An HTML page to show the list of address book entries.
  4. An HTML page to add/update/manage an entry.

That covers the broad basics, read on for the details!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Address Book Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create a test database and import 1-address-book.sql.
  • Change the database settings in 2-lib-address-book.php to your own.
  • Launch 3-list.php in the browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

ADDRESS BOOK WITH PHP MYSQL

All right, let us now get into the steps of creating an address book with PHP and MYSQL.

 

STEP 1) ADDRESS BOOK DATABASE TABLE

1-address-book.sql
CREATE TABLE `address_book` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `tel` varchar(255) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `address_book`
  ADD PRIMARY KEY (`id`),
  ADD KEY `email` (`email`),
  ADD KEY `name` (`name`),
  ADD KEY `tel` (`tel`);

ALTER TABLE `address_book`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Just a simple table to hold the address book entries.

Field Description
id Primary key, auto-increment.
name Name of the person/company.
email Email address.
tel Telephone number.
address Address.

Feel free to change to your own needs – Split to first/last name, split into mobile number, home number, work number, etc…

 

 

STEP 2) ADDRESS BOOK PHP LIBRARY

2-lib-address.php
<?php
class AddressBook {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo = null;
  private $stmt = null;
  public $lastID = null;
  public $error = "";
  function __construct () {
    try {
      $this->pdo = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
        DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
      );
    } catch (Exception $ex) { exit($ex->getMessage()); }
  }
 
  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    if ($this->stmt!==null) { $this->stmt = null; }
    if ($this->pdo!==null) { $this->pdo = null; }
  }
 
  // (C) SAVE ENTRY
  function save ($name, $email, $tel, $addr, $id=null) {
    // (C1) ADD NEW
    if ($id===null) {
      $sql = "INSERT INTO `address_book` (`name`, `email`, `tel`, `address`) VALUES (?,?,?,?)";
      $data = [$name, $email, $tel, $addr];
    }
    // (C2) UPDATE
    else {
      $sql = "UPDATE `address_book` SET `name`=?, `email`=?, `tel`=?, `address`=? WHERE `id`=?";
      $data = [$name, $email, $tel, $addr, $id];
    }
    // (C3) RUN SQL
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      $this->lastID = $this->pdo->lastInsertId();
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }
 
  // (D) DELETE ENTRY
  function del ($id) {
    try {
      $this->stmt = $this->pdo->prepare("DELETE FROM `address_book` WHERE `id`=?");
      $this->stmt->execute([$id]);
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }

  // (E) GET ENTRY
  function get ($id=null) {
    $sql = "SELECT * FROM `address_book`" . ($id==null ? "" : " WHERE `id`=?");
    $data = $id==null ? null : [$id];
    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute($data);
    return $id==null ? $this->stmt->fetchAll() : $this->stmt->fetch() ;
  }
}
 
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (G) NEW TO-DO OBJECT
$_AB = new AddressBook();

This looks massive at first, but keep calm and look carefully.

  • (A & B) When $_AB = new AddressBook() is created, the constructor automatically connects to the database. The destructor closes the connection.
  • (C to E) There are only 3 address book functions!
    • save() Add or update an address book entry.
    • del() Delete an entry.
    • get() Get entries.
  • (F & G) Self-explanatory…

 

 

EXTRA) TEST THE LIBRARY

<?php
require "2-lib-address-book.php";
 
echo $_AB->save("Jon", "jon@doe.com", "12345678", "12 Test Street")
  ? "OK" : $_AB->error;

echo $_AB->save("Jone", "jone@doe.com", "87654321", "34 Test Street")
  ? "OK" : $_AB->error;

$all = $_AB->get();
print_r($all);

That’s right, we actually have a functioning system at this point, just use the library to manage the address book. This is an important concept in modern-day development – We build a functioning system without the user interface first. The user interface can come later, which can be HTML/CSS/Javascript for a web page, or Android/iOS apps.

 

STEP 3) LIST OF ADDRESS BOOK ENTRIES

3-list.php
<!-- (A) HEADER -->
<h1>ADDRESS BOOK</h1>
<input type="button" value="Add Entry" onclick="location.href='4-entry.php'"/>
 
<!-- (B) LIST -->
<div id="list"><?php
  // (B1) LOAD LIBRARY
  require "2-lib-address-book.php";
 
  // (B2) PROCESS DELETE ENTRY
  if (isset($_GET["del"])) {
    if ($_AB->del($_GET["del"])) {
      echo "<div class='note'>Entry deleted</div>";
    } else {
      echo "<div class='note'>".$_AB->error."</div>";
    }
  }
 
  // (B3) LIST ENTRIES
  $entries = $_AB->get();
  if (is_array($entries)) { foreach ($entries as $ab) { ?>
  <div class="row">
    <div class="colA">
      <strong><?=$ab["name"]?></strong><br>
      E : <?=$ab["email"]?> | T : <?=$ab["tel"]?><br>
      <?=$ab["address"]?>
    </div>
    <div class="colB">
      <input type="button" value="Edit" onclick="location.href='4-entry.php?id=<?=$ab["id"]?>'"/>
      <input type="button" value="Delete" onclick="location.href='3-list.php?del=<?=$ab["id"]?>'"/>
    </div>
  </div>
  <?php }} else { echo "No entries found."; }
?></div>

This is not the best-looking interface design, but it should be pretty self-explanatory. We are simply using the library to get the list of entries and listing them out in HTML.

 

 

STEP 4) ADD/EDIT ADDRESS BOOK ENTRY

4-entry.php
<?php
// (A) LOAD LIBRARY
require "2-lib-address-book.php";
 
// (B) PROCESS SAVE
if (isset($_POST["name"])) {
  if ($_AB->save($_POST["name"], $_POST["email"], $_POST["tel"],
      $_POST["address"], (isset($_GET["id"])?$_GET["id"]:null))) {
    header("Location: 4-entry.php?s=1&id=" . (isset($_GET["id"])?$_GET["id"]:$_AB->lastID));
    exit();
  } else { echo "<div class='note'>{$_AB->error}</div>"; }
}
if (isset($_GET["s"])) { echo "<div class='note'>Entry Saved</div>"; }
// (C) ADDRESS BOOK ENTRY FORM
if (isset($_GET["id"])) { $entry = $_AB->get($_GET["id"]); } ?>
<form id="abform" method="post">
  <label for="name">Name</label>
  <input type="text" name="name" required value="<?=isset($entry)?$entry["name"]:""?>"/>
 
  <label for="email">Email</label>
  <input type="email" name="email" required value="<?=isset($entry)?$entry["email"]:""?>"/>
 
  <label for="tel">Telephone</label>
  <input type="text" name="tel" required value="<?=isset($entry)?$entry["tel"]:""?>"/>
 
  <label for="address">Address</label>
  <textarea name="address" required/><?=isset($entry)?$entry["address"]:""?></textarea>
 
  <input type="submit" value="Save"/>
  <input type="button" value="Back" onclick="location.href='3-list.php'"/>
</form>

Straightforward page number 2. Just use the library to get an entry, draw the HTML form. Use the library again to add/update the address book entry.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

BAREBONES SYSTEM ONLY

Yes, it’s working, but many things can be added to the project – Login protection, export to list, send the contact via email, better user interface, use AJAX to drive this project, and so much more… But that is your homework. I shall leave a couple of links below that may help.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *