In this chapter we can learn an address book in PHP where a user can login and they can add new contacts , manage contacts, update and delete the contacts.
Here I am using PDO connection and MySQL database
Login screen
Dashboard where user can manage contacts
follow some steps to complete your address book project in PHP:
Step 1
We need database and tables
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 11, 2021 at 08:49 AM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `address_book`
--
-- --------------------------------------------------------
--
-- Table structure for table `accounts`
--
CREATE TABLE `accounts` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`non_enc_pass` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `accounts`
--
INSERT INTO `accounts` (`id`, `username`, `password`, `email`, `non_enc_pass`) VALUES
(7, 'rathorji', '$2y$10$1sNJ9S0reHWeNKOyyuJUL.AQFsSl/CHnd1rfg.k1aouB0xTwLCmuK', 'gajanand.kgn@gmail.com', 'rathorji'),
;
-- --------------------------------------------------------
--
-- Table structure for table `tbl_contacts`
--
CREATE TABLE `tbl_contacts` (
`contact_id` int(11) NOT NULL,
`first_name` varchar(255) NOT NULL,
`middle_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`address` text DEFAULT NULL,
`contact_no1` varchar(255) NOT NULL,
`contact_no2` varchar(255) DEFAULT NULL,
`email_address` varchar(255) NOT NULL,
`profile_pic` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `tbl_contacts`
--
INSERT INTO `tbl_contacts` (`contact_id`, `first_name`, `middle_name`, `last_name`, `address`, `contact_no1`, `contact_no2`, `email_address`, `profile_pic`) VALUES
(20, 'Gajanand', '', 'Rathor', '', '8827213789', '', 'gajanand.kgn@gmail.com', '1618076114_Screenshot_2.png');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `accounts`
--
ALTER TABLE `accounts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tbl_contacts`
--
ALTER TABLE `tbl_contacts`
ADD PRIMARY KEY (`contact_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `accounts`
--
ALTER TABLE `accounts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT for table `tbl_contacts`
--
ALTER TABLE `tbl_contacts`
MODIFY `contact_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Step 2
Look at the file or project structure so you can create your files like this
address-book/
┣ assets/
┃ ┗ img/
┃ ┗ body-bg.jpg
┣ dashboard/
┃ ┣ profile_pics/
┃ ┃ ┣ no_avatar.png
┃ ┃ ┗ ozil.jpg
┃ ┣ config.php
┃ ┣ contacts.php
┃ ┣ footer.php
┃ ┣ header.php
┃ ┣ index.php
┃ ┣ process_form.php
┃ ┣ style.css
┃ ┗ view_contacts.php
┣ home.php
┣ index.php
┣ logout.php
┣ process_login.php
┗ style.css
Step 3
Create files & folders one by one
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Untitled</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="login-dark">
<form method="post" action="process_login.php">
<h2 class="sr-only">Login Form</h2>
<div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
<div class="form-group"><input class="form-control" type="text" name="username" placeholder="Username"></div>
<div class="form-group"><input class="form-control" type="password" name="password" placeholder="Password"></div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit">Log In</button></div><a href="#" class="forgot">Forgot your email or password?</a></form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>
proccess_login.php
<?php
include './dashboard/config.php';
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if (!isset($_POST['username'], $_POST['password'])) {
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $DB->prepare('SELECT id, password FROM accounts WHERE username = :username')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bindParam(":username", $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
if ($stmt->rowCount() > 0) {
$results = $stmt->fetchAll();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if (password_verify($_POST['password'],$results[0]['password']) == TRUE) {
// Verification success! User has logged-in!
// Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
header('Location: dashboard');
} else {
// Incorrect password
echo 'Incorrect username and/or password!';
}
} else {
// Incorrect username
echo 'Incorrect username and/or password!';
}
$DB = null;
}
logout.php
<?php
session_start();
session_destroy();
// Redirect to the login page:
header('Location: index.php');
?>
style.css
body{
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
background:#475d62 url(assets/img/body-bg.jpg);
}
.login-dark {
}
.login-dark form {
max-width:320px;
width:90%;
background-color:#1e2833;
padding:40px;
border-radius:4px;
transform:translate(-50%, -50%);
position:absolute;
top:50%;
left:50%;
color:#fff;
box-shadow:3px 3px 4px rgba(0,0,0,0.2);
}
.login-dark .illustration {
text-align:center;
padding:15px 0 20px;
font-size:100px;
color:#2980ef;
}
.login-dark form .form-control {
background:none;
border:none;
border-bottom:1px solid #434a52;
border-radius:0;
box-shadow:none;
outline:none;
color:inherit;
}
.login-dark form .btn-primary {
background:#214a80;
border:none;
border-radius:4px;
padding:11px;
box-shadow:none;
margin-top:26px;
text-shadow:none;
outline:none;
}
.login-dark form .btn-primary:hover, .login-dark form .btn-primary:active {
background:#214a80;
outline:none;
}
.login-dark form .forgot {
display:block;
text-align:center;
font-size:12px;
color:#6f7a85;
opacity:0.9;
text-decoration:none;
}
.login-dark form .forgot:hover, .login-dark form .forgot:active {
opacity:1;
text-decoration:none;
}
.login-dark form .btn-primary:active {
transform:translateY(1px);
}
files inside dashboard directory
profile_pics directory to move your upload files for profile pic
dashboard/config.php
<?php
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );
ob_start();
session_start();
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'address_book');
define('PROJECT_NAME', 'Simple Address Book');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER.':host='.DB_SERVER.';dbname='.DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD , $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
//get error/success messages
if ($_SESSION["errorType"] != "" && $_SESSION["errorMsg"] != "" ) {
$ERROR_TYPE = $_SESSION["errorType"];
$ERROR_MSG = $_SESSION["errorMsg"];
$_SESSION["errorType"] = "";
$_SESSION["errorMsg"] = "";
}
?>
dashboard/header.php
<?php
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="test">
<title><?php echo PROJECT_NAME; ?></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="row">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><span class="glyphicon glyphicon-home"></span> Site Name</a>
</div>
</div>
</div>
</div>
<div class="container">
<div class="clearfix"></div>
dashboard/footer.php
</div>
<footer>
<div class="navbar footer text-center">
<div class="container-fluid">
<div class="copyright">
<a href="https://rathorji.in" target="_blank">© Rathorji - <?php echo date("Y"); ?></a> All rights reserved
</div>
</div>
</div>
</footer>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
dashboard/index.php
<?php
require_once './config.php';
include './header.php';
/* * *****PAGINATION CODE STARTS**************** */
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
} else {
$pagenum = $_GET['pagenum'];
}
$page_limit = ($_GET["show"] <> "" && is_numeric($_GET["show"]) ) ? $_GET["show"] : 8;
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "") {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword . "%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
$last = ceil($total_count / $page_limit);
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$lower_limit = ($pagenum - 1) * $page_limit;
$lower_limit = ($lower_limit < 0) ? 0 : $lower_limit;
$sql2 = $sql . " limit " . ($lower_limit) . " , " . ($page_limit) . " ";
$stmt = $DB->prepare($sql2);
if ($keyword <> "") {
$stmt->bindValue(":keyword", $keyword . "%");
}
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
/* * *****PAGINATION CODE ENDS**************** */
?>
<div class="row">
<div class="page-header">
<h1>My contact</h1>
</div>
<?php if ($ERROR_MSG <> "") { ?>
<div class="alert alert-dismissable alert-<?php echo $ERROR_TYPE ?>">
<button data-dismiss="alert" class="close" type="button">×</button>
<p><?php echo $ERROR_MSG; ?></p>
</div>
<?php } ?>
<div class="col-lg-12" style="padding-left: 0; padding-right: 0;margin-bottom: 30px;" >
<form action="index.php" method="get" >
<div class="col-lg-6 pull-left"style="padding-left: 0;" >
<span class="pull-left">
<label class="col-lg-12 control-label" for="keyword" style="padding-right: 0;">
<input type="text" value="<?php echo $_GET["keyword"]; ?>" placeholder="search by first name" id="" class="form-control" name="keyword" style="height: 41px;">
</label>
</span>
<button class="btn btn-info" style="padding: 10px;border-radius: 0;">search</button>
</div>
</form>
<div class="pull-right" >
<a href="contacts.php" class="btn btn-info">
Add New Contact
</a>
</div>
</div>
<div class="clearfix"></div>
<?php if (count($results) > 0) { ?>
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered ">
<tbody><tr>
<th>Avatar</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact No #1 </th>
<th>Email </th>
<th>Action </th>
</tr>
<?php foreach ($results as $res) { ?>
<tr>
<td style="text-align: center;">
<?php $pic = ($res["profile_pic"] <> "" ) ? $res["profile_pic"] : "no_avatar.png" ?>
<a href="view_contacts.php?cid=<?php echo $res["contact_id"]; ?>">
<img src="profile_pics/<?php echo $pic ?>" alt="" width="50" height="50" >
</a>
</td>
<td><?php echo $res["first_name"]; ?></td>
<td><?php echo $res["last_name"]; ?></td>
<td><?php echo $res["contact_no1"]; ?></td>
<td><?php echo $res["email_address"]; ?></td>
<td>
<a href="contacts.php?m=update&cid=<?php echo $res["contact_id"]; ?>&pagenum=<?php echo $_GET["pagenum"]; ?>">
<span class="glyphicon glyphicon-edit"></span> Edit</a>
<a href="process_form.php?mode=delete&cid=<?php echo $res["contact_id"]; ?>&keyword=<?php echo $_GET["keyword"]; ?>&pagenum=<?php echo $_GET["pagenum"]; ?>" onclick="return confirm('Are you sure?')">
<span class="glyphicon glyphicon-remove-circle"></span> Delete</a>
</td>
</tr>
<?php } ?>
</tbody></table>
</div>
<div class="col-lg-12 center">
<ul class="pagination pagination-sm">
<?php
//Show page links
for ($i = 1; $i <= $last; $i++) {
if ($i == $pagenum) {
?>
<li class="active"><a href="javascript:void(0);" ><?php echo $i ?></a></li>
<?php
} else {
?>
<li><a href="index.php?pagenum=<?php echo $i; ?>&keyword=<?php echo $_GET["keyword"]; ?>" class="links" onclick="displayRecords('<?php echo $page_limit; ?>', '<?php echo $i; ?>');" ><?php echo $i ?></a></li>
<?php
}
}
?>
</ul>
</div>
<?php } else { ?>
<div class="well well-lg">No contacts found.</div>
<?php } ?>
</div>
<?php
include './footer.php';
?>
dashboard/proccess_form.php
<?php
require './config.php';
$mode = $_REQUEST["mode"];
if ($mode == "add_new" ) {
$first_name = trim($_POST['first_name']);
$middle_name = trim($_POST['middle_name']);
$last_name = trim($_POST['last_name']);
$email_id = trim($_POST['email_id']);
$contact_no1 = trim($_POST['contact_no1']);
$contact_no2 = trim($_POST['contact_no2']);
$address = trim($_POST['address']);
$filename = "";
$error = FALSE;
if (is_uploaded_file($_FILES["profile_pic"]["tmp_name"])) {
$filename = time() . '_' . $_FILES["profile_pic"]["name"];
$filepath = 'profile_pics/' . $filename;
if (!move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $filepath)) {
$error = TRUE;
}
}
if (!$error) {
$sql = "INSERT INTO `tbl_contacts` (`first_name`, `middle_name`, `last_name`, `address`, `contact_no1`, `contact_no2`, `email_address`, `profile_pic`) VALUES "
. "( :fname, :mname, :lname, :address, :contact1, :contact2, :email, :pic)";
try {
$stmt = $DB->prepare($sql);
// bind the values
$stmt->bindValue(":fname", $first_name);
$stmt->bindValue(":mname", $middle_name);
$stmt->bindValue(":lname", $last_name);
$stmt->bindValue(":address", $address);
$stmt->bindValue(":contact1", $contact_no1);
$stmt->bindValue(":contact2", $contact_no2);
$stmt->bindValue(":email", $email_id);
$stmt->bindValue(":pic", $filename);
// execute Query
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$_SESSION["errorType"] = "success";
$_SESSION["errorMsg"] = "Contact added successfully.";
} else {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = "Failed to add contact.";
}
} catch (Exception $ex) {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = $ex->getMessage();
}
} else {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = "failed to upload image.";
}
header("location:index.php");
} elseif ( $mode == "update_old" ) {
$first_name = trim($_POST['first_name']);
$middle_name = trim($_POST['middle_name']);
$last_name = trim($_POST['last_name']);
$email_id = trim($_POST['email_id']);
$contact_no1 = trim($_POST['contact_no1']);
$contact_no2 = trim($_POST['contact_no2']);
$address = trim($_POST['address']);
$cid = trim($_POST['cid']);
$filename = "";
$error = FALSE;
if (is_uploaded_file($_FILES["profile_pic"]["tmp_name"])) {
$filename = time() . '_' . $_FILES["profile_pic"]["name"];
$filepath = 'profile_pics/' . $filename;
if (!move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $filepath)) {
$error = TRUE;
}
} else {
$filename = $_POST['old_pic'];
}
if (!$error) {
$sql = "UPDATE `tbl_contacts` SET `first_name` = :fname, `middle_name` = :mname, `last_name` = :lname, `address` = :address, `contact_no1` = :contact1, `contact_no2` = :contact2, `email_address` = :email, `profile_pic` = :pic "
. "WHERE contact_id = :cid ";
try {
$stmt = $DB->prepare($sql);
// bind the values
$stmt->bindValue(":fname", $first_name);
$stmt->bindValue(":mname", $middle_name);
$stmt->bindValue(":lname", $last_name);
$stmt->bindValue(":address", $address);
$stmt->bindValue(":contact1", $contact_no1);
$stmt->bindValue(":contact2", $contact_no2);
$stmt->bindValue(":email", $email_id);
$stmt->bindValue(":pic", $filename);
$stmt->bindValue(":cid", $cid);
// execute Query
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$_SESSION["errorType"] = "success";
$_SESSION["errorMsg"] = "Contact updated successfully.";
} else {
$_SESSION["errorType"] = "info";
$_SESSION["errorMsg"] = "No changes made to contact.";
}
} catch (Exception $ex) {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = $ex->getMessage();
}
} else {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = "Failed to upload image.";
}
header("location:index.php?pagenum=".$_POST['pagenum']);
} elseif ( $mode == "delete" ) {
$cid = intval($_GET['cid']);
$sql = "DELETE FROM `tbl_contacts` WHERE contact_id = :cid";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":cid", $cid);
$stmt->execute();
$res = $stmt->rowCount();
if ($res > 0) {
$_SESSION["errorType"] = "success";
$_SESSION["errorMsg"] = "Contact deleted successfully.";
} else {
$_SESSION["errorType"] = "info";
$_SESSION["errorMsg"] = "Failed to delete contact.";
}
} catch (Exception $ex) {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = $ex->getMessage();
}
header("location:index.php?pagenum=".$_GET['pagenum']);
}
?>
dashboard/contacts.php
<?php
require_once './config.php';
include './header.php';
try {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND contact_id = :cid";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":cid", intval($_GET["cid"]));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>
<div class="row">
<div class="page-header">
<h1>Add New contact</h1>
</div>
<form class="form-horizontal" name="contact_form" id="contact_form" enctype="multipart/form-data" method="post" action="process_form.php">
<input type="hidden" name="mode" value="<?php echo ($_GET["m"] == "update") ? "update_old" : "add_new"; ?>" >
<input type="hidden" name="old_pic" value="<?php echo $results[0]["profile_pic"] ?>" >
<input type="hidden" name="cid" value="<?php echo intval($results[0]["contact_id"]); ?>" >
<input type="hidden" name="pagenum" value="<?php echo $_GET["pagenum"]; ?>" >
<fieldset>
<div class="form-group">
<label class="col-lg-4 control-label" for="first_name"><span class="required">*</span>First Name:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["first_name"] ?>" placeholder="First Name" id="first_name" class="form-control" name="first_name"><span id="first_name_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="middle_name">Middle Name:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["middle_name"] ?>" placeholder="Middle Name" id="middle_name" class="form-control" name="middle_name">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="last_name"><span class="required">*</span>Last Name:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["last_name"] ?>" placeholder="Last Name" id="last_name" class="form-control" name="last_name"><span id="last_name_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="email_id"><span class="required">*</span>Email ID:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["email_address"] ?>" placeholder="Email ID" id="email_id" class="form-control" name="email_id"><span id="email_id_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="contact_no1"><span class="required">*</span>Contact No #1:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["contact_no1"] ?>" placeholder="Contact Number" id="contact_no1" class="form-control" name="contact_no1"><span id="contact_no1_err" class="error"></span>
<span class="help-block">Maximum of 10 digits only and only numbers.</span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="contact_no2">Contact No #2:</label>
<div class="col-lg-5">
<input type="text" value="<?php echo $results[0]["contact_no2"] ?>" placeholder="Contact Number" id="contact_no2" class="form-control" name="contact_no2"><span id="contact_no2_err" class="error"></span>
<span class="help-block">Maximum of 10 digits only and only numbers.</span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="profile_pic">Profile picture:</label>
<div class="col-lg-5">
<input type="file" id="profile_pic" class="form-control file" name="profile_pic"><span id="profile_pic_err" class="error"></span>
<span class="help-block">Must me jpg, jpeg, png, gif, bmp image only.</span>
</div>
</div>
<?php if ($_GET["m"] == "update") { ?>
<div class="form-group">
<div class="col-lg-1 col-lg-offset-4">
<?php $pic = ($results[0]["profile_pic"] <> "" ) ? $results[0]["profile_pic"] : "no_avatar.png" ?>
<a href="profile_pics/<?php echo $pic ?>" target="_blank"><img src="profile_pics/<?php echo $pic ?>" alt="" width="100" height="100" class="thumbnail" ></a>
</div>
</div>
<?php
}
?>
<div class="form-group">
<label class="col-lg-4 control-label" for="address">Address:</label>
<div class="col-lg-5">
<textarea id="address" name="address" rows="3" class="form-control"><?php echo $results[0]["address"] ?></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-5 col-lg-offset-4">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
<script type="text/javascript">
$(document).ready(function () {
// the fade out effect on hover
$('.error').hover(function () {
$(this).fadeOut(200);
});
$("#contact_form").submit(function () {
$('.error').fadeOut(200);
if (!validateForm()) {
// go to the top of form first
$(window).scrollTop($("#contact_form").offset().top);
return false;
}
return true;
});
});
function validateForm() {
var errCnt = 0;
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var email_id = $.trim($("#email_id").val());
var contact_no1 = $.trim($("#contact_no1").val());
var contact_no2 = $.trim($("#contact_no2").val());
var profile_pic = $.trim($("#profile_pic").val());
// validate name
if (first_name == "") {
$("#first_name_err").html("Enter your first name.");
$('#first_name_err').fadeIn("fast");
errCnt++;
} else if (first_name.length <= 2) {
$("#first_name_err").html("Enter atleast 3 letter.");
$('#first_name_err').fadeIn("fast");
errCnt++;
}
if (last_name == "") {
$("#last_name_err").html("Enter your last name.");
$('#last_name_err').fadeIn("fast");
errCnt++;
} else if (last_name.length <= 2) {
$("#last_name_err").html("Enter atleast 3 letter.");
$('#last_name_err').fadeIn("fast");
errCnt++;
}
if (!isValidEmail(email_id)) {
$("#email_id_err").html("Enter valid email.");
$('#email_id_err').fadeIn("fast");
errCnt++;
}
if (contact_no1 == "") {
$("#contact_no1_err").html("Enter first contact number.");
$('#contact_no1_err').fadeIn("fast");
errCnt++;
} else if (contact_no1.length <= 9 || contact_no1.length > 10) {
$("#contact_no1_err").html("Enter 10 digits only.");
$('#contact_no1_err').fadeIn("fast");
errCnt++;
} else if (!$.isNumeric(contact_no1)) {
$("#contact_no1_err").html("Must be digits only.");
$('#contact_no1_err').fadeIn("fast");
errCnt++;
}
if (contact_no2.length > 0) {
if (contact_no2.length <= 9 || contact_no2.length > 10) {
$("#contact_no2_err").html("Enter 10 digits only.");
$('#contact_no2_err').fadeIn("fast");
errCnt++;
} else if (!$.isNumeric(contact_no2)) {
$("#contact_no2_err").html("Must be digits only.");
$('#contact_no2_err').fadeIn("fast");
errCnt++;
}
}
if (profile_pic.length > 0) {
var exts = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
var get_ext = profile_pic.split('.');
get_ext = get_ext.reverse();
if ($.inArray(get_ext[0].toLowerCase(), exts) <= -1) {
$("#profile_pic_err").html("Must me jpg, jpeg, png, gif, bmp image only..");
$('#profile_pic_err').fadeIn("fast");
}
}
if (errCnt > 0)
return false;
else
return true;
}
function isValidEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
</script>
<?php
include './footer.php';
?>
dashboard/view_contacts.php
<?php
require_once './config.php';
include './header.php';
try {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND contact_id = :cid";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":cid", intval($_GET["cid"]));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>
<div class="row">
<ul class="breadcrumb">
<li><a href="index.php">Home</a></li>
<li class="active">View Contacts</li>
</ul>
</div>
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">View Contact</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" name="contact_form" id="contact_form" enctype="multipart/form-data" method="post" action="process_form.php">
<fieldset>
<div class="form-group">
<label class="col-lg-4 control-label" for="first_name"><span class="required">*</span>First Name:</label>
<div class="col-lg-5">
<input type="text" readonly="" placeholder="First Name" value="<?php echo $results[0]["first_name"] ?>" id="first_name" class="form-control" name="first_name"><span id="first_name_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="middle_name">Middle Name:</label>
<div class="col-lg-5">
<input type="text" readonly="" value="<?php echo $results[0]["middle_name"] ?>" placeholder="Middle Name" id="middle_name" class="form-control" name="middle_name">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="last_name"><span class="required">*</span>Last Name:</label>
<div class="col-lg-5">
<input type="text" readonly="" value="<?php echo $results[0]["last_name"] ?>" placeholder="Last Name" id="last_name" class="form-control" name="last_name"><span id="last_name_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="profile_pic">Profile picture:</label>
<div class="col-lg-5">
<?php $pic = ($results[0]["profile_pic"] <> "" ) ? $results[0]["profile_pic"] : "no_avatar.png" ?>
<a href="profile_pics/<?php echo $pic ?>" target="_blank"><img src="profile_pics/<?php echo $pic ?>" alt="" width="100" height="100" class="thumbnail" ></a>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="email_id"><span class="required">*</span>Email ID:</label>
<div class="col-lg-5">
<input type="text" readonly="" value="<?php echo $results[0]["email_address"] ?>" placeholder="Email ID" id="email_id" class="form-control" name="email_id"><span id="email_id_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="contact_no1"><span class="required">*</span>Contact No #1:</label>
<div class="col-lg-5">
<input type="text" readonly="" value="<?php echo $results[0]["contact_no1"] ?>" placeholder="Contact Number" id="contact_no1" class="form-control" name="contact_no1"><span id="contact_no1_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="contact_no2">Contact No #2:</label>
<div class="col-lg-5">
<input type="text" readonly="" value="<?php echo $results[0]["contact_no2"] ?>" placeholder="Contact Number" id="contact_no2" class="form-control" name="contact_no2"><span id="contact_no2_err" class="error"></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label" for="address">Address:</label>
<div class="col-lg-5">
<textarea id="address" readonly="" name="address" rows="3" class="form-control"><?php echo $results[0]["address"] ?></textarea>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<?php
include './footer.php';
?>
dashboard/style.css
.page-header h1{
font-size: 32px;
}
Note: if having problem to desire results you can download zip file of source code.