Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/329ea1887adf4b91483ad0f5d8af66ec to your computer and use it in GitHub Desktop.
Save code-boxx/329ea1887adf4b91483ad0f5d8af66ec to your computer and use it in GitHub Desktop.
PHP MYSQL Address Book

PHP MYSQL ADDRESS BOOK

https://code-boxx.com/simple-address-book-php-mysql/

NOTES

  1. Create a test database and import 1-address-book.sql.
  2. Change the database settings in 2-lib.php to your own.
  3. Launch 4a-book.php in the browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `address_book` (
`id` bigint(20) 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=utf8mb4;
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` bigint(20) NOT NULL AUTO_INCREMENT;
<?php
class AddressBook {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $lastID = null;
public $error = "";
function __construct () {
$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
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt!==null) { $this->stmt = null; }
if ($this->pdo!==null) { $this->pdo = null; }
}
// (C) EXECUTE SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET ENTRY
function get ($id=null) {
$this->query(
"SELECT * FROM `address_book`" . ($id==null ? "" : " WHERE `id`=?"),
$id==null ? null : [$id]
);
return $id==null ? $this->stmt->fetchAll() : $this->stmt->fetch() ;
}
// (E) SAVE ENTRY
function save ($name, $email, $tel, $addr, $id=null) {
// (E1) NEW OR UPDATE
if ($id===null) {
$sql = "INSERT INTO `address_book` (`name`, `email`, `tel`, `address`) VALUES (?,?,?,?)";
$data = [$name, $email, $tel, $addr];
} else {
$sql = "UPDATE `address_book` SET `name`=?, `email`=?, `tel`=?, `address`=? WHERE `id`=?";
$data = [$name, $email, $tel, $addr, $id];
}
// (E2) RUN
$this->query($sql, $data);
return true;
}
// (F) DELETE ENTRY
function del ($id) {
$this->query("DELETE FROM `address_book` WHERE `id`=?", [$id]);
return true;
}
}
// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (H) ADDRESS BOOK OBJECT
$_AB = new AddressBook();
<?php
if (isset($_POST["req"])) {
require "2-lib.php";
switch ($_POST["req"]) {
// (A) GET ENTRY/ENTRIES
case "get":
echo json_encode($_AB->get(
isset($_POST["id"]) ? $_POST["id"] : null
));
break;
// (B) SAVE ENTRY
case "save":
$_AB->save(
$_POST["name"], $_POST["email"], $_POST["tel"], $_POST["addr"],
isset($_POST["id"]) ? $_POST["id"] : null
);
echo "OK";
break;
// (C) DELETE ENTRY
case "del":
$_AB->del($_POST["id"]);
echo "OK";
break;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Address Book</title>
<script src="4b-book.js"></script>
<link rel="stylesheet" href="4c-book.css">
</head>
<body>
<!-- (A) ADDRESS BOOK LIST -->
<div id="abWrap">
<div id="abAdd" class="row" onclick="ab.tog(true)">+</div>
<div id="abList"></div>
</div>
<!-- (B) ADDRESS BOOK ENTRY -->
<form id="abForm" class="hide" onsubmit="return ab.save()">
<label>Name</label>
<input type="text" id="abName" required>
<label>Email</label>
<input type="email" id="abEmail" required>
<label>Telephone</label>
<input type="text" id="abTel" required>
<label>Address</label>
<textarea id="abAddr" required></textarea>
<input type="hidden" id="abID">
<input type="button" value="Back" onclick="ab.tog()">
<input type="submit" value="Save">
</form>
</body>
</html>
var ab = {
// (A) HTML ELEMENTS
hWrap : null, // address book list wrapper
hList : null, // address book list
hForm : null, // address book form
hfName : null, // name field
hfEmail : null, // email field
hfTel : null, // tel field
hfAddr : null, // address field
hfID : null, // id field
// (B) INIT - GET HTML ELEMENTS + LOAD LIST
init : () => {
ab.hWrap = document.getElementById("abWrap");
ab.hList = document.getElementById("abList");
ab.hForm = document.getElementById("abForm");
ab.hfName = document.getElementById("abName");
ab.hfEmail = document.getElementById("abEmail");
ab.hfTel = document.getElementById("abTel");
ab.hfAddr = document.getElementById("abAddr");
ab.hfID = document.getElementById("abID");
ab.list();
},
// (C) HELPER - AJAX FETCH
ajax : (data, after) => {
// (C1) FORM DATA
let form = new FormData();
for (let [k,v] of Object.entries(data)) { form.append(k,v); }
// (C2) AJAX FETCH
fetch("3-ajax.php", { method:"post", body:form })
.then(res => res.text())
.then(res => after(res))
.catch(err => console.error(err));
},
// (D) TOGGLE HTML SECTION
tog : id => {
// (D1) ADD/EDIT ADDRESS BOOK ENTRY
if (id) {
ab.hWrap.classList.add("hide");
ab.hForm.classList.remove("hide");
ab.hForm.reset();
if (Number.isInteger(id)) {
ab.ajax({ req : "get", id : id }, e => {
e = JSON.parse(e);
ab.hfName.value = e.name;
ab.hfEmail.value = e.email;
ab.hfTel.value = e.tel;
ab.hfAddr.value = e.address;
ab.hfID.value = id;
});
} else { ab.hfID.value = ""; }
}
// (D2) SHOW ADDRESS BOOK LIST
else {
ab.hForm.classList.add("hide");
ab.hWrap.classList.remove("hide");
}
},
// (E) LOAD ADDRESS BOOK LIST
list : () => ab.ajax({ req : "get" }, entries => {
ab.tog();
entries = JSON.parse(entries);
ab.hList.innerHTML = "";
if (entries.length>0) { for (let e of entries) {
let row = document.createElement("div");
row.className = "row";
row.innerHTML = `<div class="rInfo">
<div class="rOne">${e.name}</div>
<div class="rTwo">${e.email} | ${e.tel}</div>
<div class="rTwo">${e.address}</div>
</div>
<button class="rBtn" onclick="ab.del(${e.id})">X</button>
<button class="rBtn" onclick="ab.tog(${e.id})">&#9998;</button>`;
ab.hList.appendChild(row);
}}
}),
// (F) SAVE ADDRESS BOOK ENTRY
save : () => {
// (F1) FORM DATA
let data = {
req : "save",
name : ab.hfName.value,
email : ab.hfEmail.value,
tel : ab.hfTel.value,
addr : ab.hfAddr.value,
id : ab.hfID.value
};
if (data.id=="") { delete data.id; }
// (F2) AJAX SAVE
ab.ajax(data, res => {
if (res=="OK") { ab.list(); }
else { alert(res); }
});
return false;
},
// (G) DELETE ADDRESS BOOK ENTRY
del : id => { if (confirm("Delete entry?")) {
ab.ajax({ req : "del", id : id }, res => {
if (res=="OK") { ab.list(); }
else { alert(res); }
});
}}
};
window.onload = ab.init;
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
.hide { display: none !important; }
body {
max-width: 400px;
padding: 10px;
margin: 0 auto;
background: #f7f7f7;
}
/* (B) ADDRESS BOOK LIST */
.row {
padding: 15px;
margin-bottom: 10px;
display: flex;
align-items: stretch;
border: 1px solid #efefef;
background: #fff;
}
#abAdd {
color: #5a6eb7;
font-size: 30px;
justify-content: center;
cursor: pointer;
}
.rInfo {
flex-grow: 1;
}
.rOne { font-weight: 700; }
.rTwo {
margin-top: 5px;
font-size: 14px;
color: #333;
}
.rBtn {
padding: 0 8px;
font-size: 24px;
border: 0;
color: #5a6eb7;
background: 0;
cursor: pointer;
}
/* (C) ADDRESS BOOK ENTRY FORM */
#abForm {
padding: 20px;
border: 1px solid #ebebeb;
background: #fff;
}
#abForm label, #abForm input[type=text], #abForm input[type=email], #abForm textarea {
display: block;
width: 100%;
}
#abForm label {
color: #a5a5a5;
margin: 10px 0;
}
#abForm label:first-child { margin-top: 0; }
#abForm input[type=text], #abForm input[type=email], #abForm textarea {
padding: 10px;
border: 1px solid #e1e1e1;
resize: none;
}
#abForm input[type=button], #abForm input[type=submit] {
margin-top: 20px;
padding: 10px;
border: 0;
cursor: pointer;
color: #fff;
background: #5a6eb7;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment