Author: Benedict Daniel Masimbani
Viewers: 82
Last month viewers: 4
Categories: PHP Tutorials
In this article you will learn:
Who is this Article For
Process
Project Requirements
Requirements in this Project
Requirements in Wireframes
LAMP Stack Infrastructure Provisioning
Infrastructure in this Project
Database Design and Build with Data Preparation
Database Scripting
Interacting with the MySQL Client
Checking the Database
Adding the New MySQL User
Test Data
Project Folder Structuring and Utility Functions Coding
Project Folder Structure
Project folder in Relation to Document Root
Utility Functions
Database Connectivity
Writing the Connection Class
CRUD You Need to Know This
Coding Functions
Closing Notes on Utility Functions
Frontend Development
Code Contact List
Editing Web Server Configuration
Contact Add Form
Elaborations on Add Contact Forms Functionality
Edit Contact Form
Closing Notes
Backend Development
What is Next?
About the Author
Who is this Article For
To understand this tutorial without difficult a basic understating of PHP, SQL syntax, HTML, CSS and familiarity with any Linux operating system distribution such as Debian or Ubuntu is assumed.
If you do not meet any of the above requirements, I would advise you to find yourself introductory texts or tutorials grasp the fundamentals and come to this illustrative tutorial to get the bread and butter.
To put this right I would say LAMP stack address book project is a sample software development project which is to showcase how to develop a Web application utilizing Linux, Apache, MySQL and PHP that is known as the LAMP stack for beginner and intermediate PHP developers.
Process
In order to embark with the project it is very important to highlight the major steps and milestones which will serve as road map helping us to make evaluation on whether will are on right track and stay focused on the project goals.
It is of great importance however to realize that some steps may overlap due to dependency nature of work. The followings are major steps in our lamp stack Address Book project:
● Define Key Project Requirement
● How to Prepare the infrastructure, installation and configuration
● Database Design and Build with Test Data Preparation
● Project Folder Structuring, connection component and utility functions write up
● Frontend Development
● Backend Development
● Integration and deployment to production
Project Requirements
The project requirements are to give directions to the project manager and his team about the final product required by the client/sponsor of the project.
The requirements help the manager and his/her team to focus on building a product that meets the user expectations as defined in the specifications of product in project agreement or contract document signed between the client and representative and project engineering contractor.
Requirements in this Project
● There should be a list showing all entries of contacts that have been stored in the address book
● Every entry(above) should consist of fields name, first name, email, street, zip code and a city whereby a city should be a drop down with cities defined in a table in the database
● A form to add new entry
● A form to edit existing entries in the database
● And so forth the list continues
Requirements in Wireframes
Wireframes are simple sketches of the product to be developed. They serve as models helping to clear understanding on how the software sought to be built features will look like by both client and contractor.
In other words we can say wireframes are like map showing features of a given landscape or a building. Wireframe are one of the low fidelity prototypes which are used as blueprints before the software development project gets underway.
There are many prototyping tools to generate wireframes out there. Examples of prototyping softwares are Adobe XD, Axure RP and pencil project which is open source.
If your are familiar with any such design software the choice is your on what to use to make the wireframes. It is very easy for one to get started prototyping with pencil project software. All of the ftwo designs just to grasp the idea of product to be developed were designed with the pencil software: Contact edit form and Contact List Form.
You may download pencil protoyping software from the Pencil download page.
For more details about wireframing please find the textbook Wireframing Essentials "An Introduction to User Experience Design by Mathew J Hamm.
LAMP Stack Infrastructure Provisioning
Provisioning is all about providing for installation and configuration of required softwares and their dependencies for a given environment and or platform.
There are a number of ways to provision the LAMP stack in development, staging and production environments. Development environment is the local one for coding prior shipping code to other (staging and production environment).
Usually the development environment is characterized by having a lot of debugging among many other preliminary development activities such as unit testing and the like.
Staging environment is there for massive testing to satisfy both functional, non-functional and user requirement before deploying the code to production.
The staging environment is made in such a way that it tries to emulate the production environment where the finished software product is going to be deployed and maintained.
Production environment is the ultimate destination of highly tested and optimized code for achieving business operation tasks required to be done for the business.
For the sake of simplicity we will postpone the discussion of staging and production environments in this tutorial until the coming series of this tutorial series. If you would like to get deep in provisioning you may find a text "Creating Development environment with vagrant" by Michael Peacock.
Infrastructure in this Project
To quickly install lamp stack in Ubuntu Debian Linux OS distro make sure you have reliable a Internet connection locate the terminal or command line in your computer operating system and launch it.
After launching the terminal write the following command sudo apt-get install lampserver^ -y
and click enter button on your computer keyboard and then wait for the installation to proceed.
At one time you shall be required to enter/set the MySQL root account’s password, please do that by entering the password that you will remember and wait for the installation process to finish up.
After the installation you can check for Apache2, MySQL and PHP by entering the following commands that appear in each line below in your terminal and click the enter button respectively after issuing each one of the commands specified.
apache2 -v
mysql -v
php -v
For each of the above you will get version number of the software as evidence/proof of installation in the system you are using.
Furthermore you may visit your site by typing localhost or localhost’s loopback IP address: 127.0.0.1 through your web browser program address bar.
Once we are done now with the infrastructure stuff we should pull our sleeves and get ready for the next lesson where we will be dealing with the database stuff.
Database Design and Build with Data Preparation
One of famous database writer C J Date defines Database as the operational data for the enterprise. We will be Taking Our Address Book application as a little demo of database driven application in this scenario.
Databases are normally managed by a special dedicated software system or subsystem known as database management systems [DBMS] such as MySQL, Oracle, Postgres and SQL server. For the sake of this project we will be using MySQL which comes bundled in our LAMP stack.
Before going further let’s revisit our case by doing a quick recap on Requirements in this project.
From requirement number 2 and 3, it can be postulated that our little project requires at least two tables in its database to get going.
We shall call our database contactdb and the tables contact and city. From the user story/narration we may deduce that schema for table city to be city:( id, city_name) and for the table contact to be contact:(id, name, firstname, email, street, zip_code, cityid) where id serve as the surrogate primary key and cityid as foreign key in table contact referencing id in table city.
Database Scripting
With our database description well outlined it is time to make our database generation script that will be used later to create and recreate database once needed later.
This is very useful option when creating database driven applications since the database script once written can be used several times to regenerate the given database and even edited occasionally and reused many times if needed.
You may use text editor of your preference to make the database script but ones with syntax highlighting feature support.
The syntax highlighting editor like emacs and vi editors available in Linux become very useful as they come with syntax support feature that can alert you of any of your syntax error immediately.
There are many text editors for Linux, UNIX and Windows platform you can get a long list of those editors(some for free, paid or free trial) by searching them online with any of the big search engines like google, bing or yahoo.
If you lack syntax highlighting text editor hurry up and get one whether, free or paid depending on your budget and preference.
With your text editor up and running open it and paste the following code [in bold] into writing area:
Create database if not exist contactdb; use contactdb create table city( id smallint unsigned not null primary key auto_increment, city_name varchar(50) not null ) engine innodb; create table contact( id int(10) unsigned not null primary key auto_increment, name varchar(80) not null, firstname varchar(25) not null, email varchar(125) unique not null, street varchar(25) not null, zip_code int(5) not null, cityid smallint unsigned not null, foreign key(cityid) references city(id) ) engine innodb;
Once your done with pasting save the document as contactdb.sql in your Documents or home directory folder.
Hint: MySQL comes supported with several engine such as myisam and innodb and so forth. Of the two engines mentioned above it is innodb that comes up with relational constraint enforcement that is useful for checking referential intergrate across several database tables which is important for the scenario such as ours.
The use of innodb engine strictly enforced by writing engine innodb at the end of table creation statement script.
This is so since some mysql comes with innodb and myisam engine and it might be the case that myisam engine is the default. If you do not put that in table creation statement you may end up with myisam engine tables.
Else you may have to check for mysql engine configurations before running script in the terminal.
For further learning about mysql grab the book MySQL DATABASE USAGE AND ADMINISTRATION by Vikram Vaswani.
Interacting with the MySQL Client
With our database script now properly written up it is time to run the database generation script to create our contactdb database in our locally provisioned lamp stack server. Launch the terminal on your computer and issue the following command to generate the database in the lamp stack server. Rememeber you have to click your computer keyboard’s enter button after writing the command to invoke it.
mysql -h localhost -u root -p password
insert the root password then issues the following command create database contactdb; After creating the database exit the mysql shell by issuing a fllowing command exit Now in the shell terminal issue the following command
mysql -h localhost -u root contactdb < /home/user/contactdb.sql -p password
Insert the root password and click enter if everything is Ok and password is correct the command shell will just move to $, otherwise you will see errors.
NOTE! Substitute /home/user/contactdb.sql with the right absolute path of the contactdb.sql depending on where you saved it. So if you saved your contactdb.sql in /home/user/Document/ .
Also the user in above case represent the linux machine account’s username for example in my local development the username is benedict so the correct path will be /home/benedict/Document.
Alternatively you may change your working directory to the path where the contactdb.sql is, by issuing command
cd /home/user/Documents
pressing enter will change the command shell path to /home/user/Documents :
$ /home/user/Documents$ mysql -h localhost -u root contactdb < contactdb.sql -p
As you can see taking the alternative option eliminates the need for you to right the absolute file path in the command statement for this case the choice is your whatever method you prefer that is up to you.
Checking the Database
After running the previous command there is a need to check our MySQL database to see if there are update to our contactdb database.
Given the command executed well hopeful our database should have been updated by now, to confirm that open the terminal and follow the procedures outline here under.
mysql -h localhost – u root -p password
enter the correct root password issue the following command into the mysql shell.
use contactdb
then issue the show table command show tables; now our two tables i.e city and contact can be seen furthermore by issuing describe table_name; command where table_name is one of our tables in the contactdb database the details about particular table can be seen on the screen describe city;
The appearance of tables listed and their details seen as defined in our database generation script confirms that the database creation/update went right.
Adding the New MySQL User
Input the following command to add new mysql user
create user onlineuser@'localhost' identified by password 'Pas5w#rd';
Issue the following command to grant limited database access privileges to the user just created:
grant select, insert, update on contactdb.* to 'onlineuser'@'localhost'; flush privileges;
This onlineuser is the new one with limited privileges granted just to be on the safe side.
Take this as a rule "it is not advisable to allow root user remote login to mysql as such this my jeopardize the server security by making it prone/vulnerable to attacks with elevated privileges.
Also take this as plus limit the privilages of online user to a set of minimum just required to make him/her do the job she is supposed to given the database schema belonging to him/her.
For futher details about database security you may read the book Database Adminstration by Craig Mullins.
We will later on be using this onlineuser account to access the database of our Address Book application
Test Data
To wind up this database stuff for now, go and launch your text editor once again and paste the following PHP code into the writing area and save it as Test_Data.php in datadir folder of our address book project we will be using it later.
<?php $cities=[ "LONDON", "LIVERPOOL", "LYON", "DORTMOND", "MADRID", "LEICESTER", "BERLIN" ]; $contacts=[ ["Bernd Lenno",Bernd,"lenno@afc.com","Ashburton Groove",55105,1], ["Jurgen Klop",Jurgen,"klop@lfc.com",Anfield,54104,2], ["Nicolous Pepe",Nicolous,"pepe@afc.com","AshBurton Groove",55105,3], ["Pierre Aubemeyang",Pierre,"pam@afc.com","AshBurton Groove",55105,4], ["Per Mertsacker",Per,"bfg@afc.com","AshBurton Groove",55105,4] ]; ?>
Project Folder Structuring and Utility Functions Coding
There are number of options when its comes to the structure of project folder/directory. Though there are no strict guidelines there are some good rules to observe in organizing the project code and resource files for the sake of easy maintainability and clarity.
For our case of vanilla programming style we have great degree of freedom on how we write and organize our code compared to if someone is writing code for a given PHP coding framework.
There is a noted tendency of some frameworks to minimize flexibility and requiring programmers to write code that follows particular pattern or convention chosen by the framework pioneers or maintainers.
Whatever the style you wish to follow it is better to write a program code in such a way that embrace the separation of concerns and reduces coupling of code so that we could afford easy integration between components of the software developed.
Project Folder Structure
In our Address Book project we shall have at most three folders/directories within the main project folder as now described.The three folders are html, includes and datadir.
In the html folder all the frontend work will be put there. These frontend includes the content structure code(html) files, the content presentation stylesheets (css) files, Web site logo(favicon.png) image and finnaly the content behaviour functionalities (javascript) files.
In the includes folder all the backend work will be put there. These backend includes the utility functions file for common repeated operations, database connectivity component and some specific backend files related to specific frontend files functionalities.
In the the datadir folder all other less frequently used assets like Test_Data.php files and database generation script will be put for storage.
Project folder in Relation to Document Root
By default the web document root is set to /var/www/html in debian Ubuntu Linux distribution upon installation of the lamp-server.
This(web document root directory) is the one holding the index.php file that is shown once you complete the LAMP server installation and visiting the localhost via the browser immediately after successful installation.
It is possible though to change this web document root by changing the configuration in the Apache HTTP server configuration files.
That is done by editing the DocumentRoot setting in server configuration replacing DocumentRoot /var/www/html with our new document root folder tree like /home/user/Desktop/LAMP/html as shown below:
Document root /home/benedict/LAMP/html
In my case the user is benedict . Please make sure to substitute the right username for your Linux machine user account name to get the right folder and file path.
In fact this is very useful if you are to make your project well easily composable with the PHP dependency management tool known as the composer where you can incorporate and integrate other packages and APIs functionalities into the system that you are building.
Do not forget to restart the apache2 server to make it reload the new configuration, so that the applied change may take effect.
Two ways to restart Apache HTTP server are by issuing the either of the following commands via the command terminal of your Linux machine.
You should have the sudo password to make any of them tick.
sudo apache2 restart
sudo service apache2 reload
After that make sure that the apache user is given read and write access to the new DocumentRoot folder.
Alternatively you may leave the /var/www/html as the default document root in apache http server configuration and simply utilize Linux’s symbolic links between your project folder and the /var/www/html directory.
For more details about Linux link files please find the text Linux Administrators: a Beginner's Guide by Wale Soyinka.
Well, for simplicity and brevity we may leave without changing the default DocumentRoot for now as these issues of changing DocumentRoot directory and developing easily composable PHP project and integration as awhole will discussed in the coming tutorials in this series of tutorials.
Utility Functions
As it was said earlier the utility functions are those which do common repeated operations within the application.
There are many such operations in Web applications good example candidate task could be writing a top banner indicating whether the user has signed in or out on each page served on the site and also a footer strip at the bottom of the site in a dynamic web application.
We could divide web sites into two types: one Static and the other Dynamic depending on the dynamic nature of content shown on them.
Static websites are those whose content change only when the webmaster updates the site content while Dynamic sites are those which whose content change depending on the user interaction with the site like logging in/sign in or log of/sign out and posting comments or posts in social media sites.
Not only that but also dynamic sites involve great deal of interaction with the database updated in the real time/almost real time like doing Internet banking where on line mobile money transaction are performed and user accounts get credited or debited upon completion of such transaction.
Database Connectivity
Database connectivity is another issue which is frequently needed to complete user web application interaction cycle in a dynamic/data driven web application.
Due to a lot interactivity performed there comes importance of devising a proper mechanism of handling database connectivity issue by assigning all database handling responsibilities to a given component that can be instantiated by following the common standard rather than reinventing the wheel by performing each database call in disorganized fashion.
We shall be looking on the utility functions and database connection/connectivity in this section while the look on backend specific function logic application as far as these functions are applied will be withheld until we reach to the Backend lesson Before Moving to coding here goes the list our utility functions:
1. cleansData()
2. footNoting
3. getContactByEmail
4. getContactById
5. listAllContacts
6. addContact
7. editContact
8.addCity
9.tabulate
10. listCities
Prior to coding the above function we shall look on creating our database connectivity component which we shall call class connection.
Writing the Connection Class
This is one component that has been written in an object oriented paradigm. Launch the text editor you are using for coding. Paste the following code into the writing area.
<?php
class connection { protected static $_instance = null;
public static function instance() { if(!isset(self::$_instance)) {
self::$_instance = new connection(); } return self::$_instance; }
public function getconnection() {
$unix = "localhost"; $socket = ''; $db= "contactdb"; $user = "onlineuser"; $passwd ="Pas5w#rd"; $dsn="mysql:host=$unix;unix_socket = $socket;dbname=$db"; $conn = new PDO($dsn, "$user", "$passwd"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn;
} } ?>
CRUD You Need to Know This
The term CRUD is an acronym for create, read, update and delete.
This term comes up most of the time when we discussing about database driven application since most of the time we talk about data operations; like adding a record(row), removing a record(row), editing some or almost all fields in a given record(row), finding a particular record(row) in the database table.
We deal with SQL(sequential query language) terms such as insert which refers to create, select which refers to read, update refers to modification/editing of a record in a database table. and delete refers to removal of particular record from the database table.
With the exception of footNoting and tabulate functions all the rest of the next 10 functions which are going to be written as utility functions contains one among the four CRUD operation to be precisely they contain one among three CRUD operation which are create, read and update.
The delete command won’t be touched now until later.
If you are new to the SQL language I will advise you to grab on of introductory text or ebook on the SQL subject.
One of such text is SQL tutorial from tutorialspoint.com.
In our application we will be using PHP PDO MySQL Driver simply because it is not only object oriented but also easily maintainable as it support several DBMS like Oracle, Postgress, SQLServer and many more.
This makes it useful when the company decides to switch from one DBMS to another, there is no big maintenance work to be done besides little modification in the connection class compared to if someone could be using the PHP MySQLi driver which is for MySQL DBMS only.
Coding Functions
function ListAllContacts($db)The function getContactById is used to get a single contact filtering by ID matching function:
{
$sql='select * from contact join city on contact.cityid=city.id order by contact.id desc';
$stmt=$db->prepare($sql);
$stmt->execute();
$result=$stmt->fetchAll();
return $result;
}
getContactById($db,$contactid)
{
$sql='select * from contact join city on contact.cityid=city.id where contact.id=:id';
$stmt=$db->prepare($sql);
$stmt->bindParam(':id',$id);
$id=$contactid;
$stmt->execute();
$result=$stmt->fetchAll();
return $result;
}
function listCities function listCities($db)
{
$sql='select * from city order by id';
$stmt=$db->prepare($sql);
$stmt->execute();
$result=$stmt->fetchAll();
return $result;
}
function getContactByEmail($db,$emailId)
{
$sql='select * from contact c join city t on c.cityid=t.id where email=:email';
$stmt=$db->prepare($sql);
$stmt->bindParam(':email',$email);
$email=$emailId;
$stmt->execute();
$result=$stmt->fetchAll();
return $result;
}
function addContact($db,$contact)
{
$sql='insert into contact(name,firstname,email,street,zip_code,cityid) values(:name, :firstname, :email, :street, :zip_code, :cityid)';
$stmt=$db->bindParam(':name',$name);
$stmt=$db->bindParam(':firstname',$firstname);
$stmt=$db->bindParam(':email',$email);
$stmt=$db->bindParam(':street',$street);
$stmt=$db->bindParam(':zip_code',$zip_code);
$stmt=$db->bindParam(':cityid',$cityid);
$name=$contact[0];
$firstname=$contact[1];
$email=$contact[2];
$street=$contact[3];
$zip_code=$contact[4];
$cityid=$contact[5];
$result=$stmt->execute();
return $result;
}
The function footNoting writes footer notices:
function footNoting()
{
$date = new DateTime("now");
$tar=$date->format('Y');
echo '<p>';echo "©$tar Benedict Daniel Masimbani"; echo '</p>';
}
The function tabulate is there to write record rows to the table be outputed to the screen view.
function tabulate($list)
{The function addCity is used to add a named city.
for($i=0;$i<count($list);$i++)
{
$id=$list[$i][0];
$name=$list[$i]['name'];
$firstname=$list[$i]['firstname'];
$email=$list[$i]['email'];
$street=$list[$i]['street'];
$zip_code=$list[$i]['zip_code'];
$city_name=$list[$i]['city_name'];
echo'<tr>';
echo"<td>$name</td>";
echo"<td>$firstname</td>";
echo"<td>$email</td>";
echo"<td>$street</td>";
echo"<td>$zip_code</td>";
echo"<td>$city_name</td>";
echo'<td><a href="editcontact.php?id='.$id.'"><button class="button">Edit</button></a>';
echo'</tr>';
}
}
function addCity($db,$cityname)
{
$sql='insert into city(city_name) values(:city_name)';
$stmt=$db->bindParam(':city_name',$city_name);
$city_name=$cityname;
$result=$stmt->execute(); return $result;
}
The cleansData function is used to sanitize the data once posted on the sever side.
function cleansData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function editContact($db,$contactid,$updatedFields)
{
$name=$updatedFields[0];
$firstname=$updatedFields[1];
$email=$updatedFields[2];
$street=$updatedFields[3];
$zip_code=$updatedFields[4];
$cityid=$updatedFields[5];
$sql="update contact set name='$name', firstname='$firstname', email='$email', street='$street', zip_code='$zip_code', cityid='$cityid' where id=:id";
$stmt=$db->prepare($sql);
$stmt->bindParam(':id',$id);
$id=$contactid;
$result=$stmt->execute();
return $result;
}
Closing Notes on Utility Functions
All the eight utility functions needs to be written in a single file lets call it utility.php between <?php and ?> .
Tags as hereunder portrayed for the PHP parser to parse them correctly without throwing errors.
<?php
function addContact($db,$contact)
{
} function getContactByEmail($db,$emailId) { } function getContactById($db,$id) { } function ListAllContacts($db) { } function editContact($db, $contactid) { } function addCity($db,$city_name) { } function listCities($db) { } function tabulate($list) { } function footNoting() { } function cleansData() { } ?>
What goes between the curly braces is particular function logic as written previously I have chosen not to write them here just for brevity since the slide space is limited so don’t forget to put them into their place as shown in the preceding slides.
We shall see the usefulness of these functions once we start integrating and running the application functionalities.
Frontend Development
The frontend is the part of the system in which the user interaction with the system is performed.
As described earlier our frontend is built up of mostly content structure by HTML tags, presentation stylesheets by CSS and a little of behavior code by JavaScript.
We won't be covering JavaScript in this edition, some JavaScript coverage will be discussed in the coming serie of tutorials.
Lets start by coding the reusable content-less HTML page template. Launch your text editor and paste the following code in the writing area.
<!Doctype html> <html>
<head>
<title>Title Goes Here </title>
<link rel="stylesheet" href="https://www.ajax-cdn/foundation/css/min.css"/>
<script> </script>
</head>
<body>
<header><h1>Address Book</h1></header> <nav>
<ul> <li class="button success" style="displaly:inline-block;"><a href="addcontact.html" style="text- decoration:none;">Add Contact</a></li>
<li class="button success" style="displaly:inline-block;"><a href="listcontacts.html" style="text- decoration:none;"> Contact List</a></li>
</ul> </nav>
<section> </section>
<footer> </footer>
</body>
</html>
This template saves as a foundation for us to be writing other frontend pages quickly following the modern HTML5 standard with semantic mark up.
It will be reused several times so save it as template.html in Deskop or any location of your choice easy for you to remember.
We shall just be copying and editing it to write our frontend pages eliminating the need to write everything from the scratch every time we need to make such pages.
Code Contact List
Copy the template.html written previously and edit it to make it resemble the one shown hereunder.
<!Doctype html>
<html>
<head>
<title>List of Contacts</title>
<link rel="stylesheet" href="https://www.ajax-cdn/foundation/css/min.css"/>
</head>
<body>
<?php
require_once("../connection.php");
require_once("../utility.php");
?>
<header><h1>Address Book</h1> </header>
<nav> <ul> <li class="button success" style="displaly:inline-block;"><a href="addcontact.html" style="text- decoration:none;">Add Contact</a></li>
<li class="button success" style="displaly:inline-block;">
<a href="listcontacts.html" style="text-decoration:none;"> Contacts List</a></li>
</ul>
</nav>
<section>
<table>
<thead>
<th>Name</th>
<th>Firstname</th>
<th>Email</th>
<th>Street</th>
<th>Zip Code</th>
<th>City</th>
<th>Action</th>
</thead>
<tbody>
<?php $conn=new connection(); //instatiating our connection object $db=$conn->getconnection(); $list=ListAllContacts($db); tabulate($list); ?> </tbody> </table> </section> <footer><?php footNoting(); ?></footer> </body> </html>
As it can be noted the bold text in the previous code is the one which have been added after editing even though the script tag was removed from the head section of our html since we don't need it now as we won't bring JavaScript yet.
If we had data filled in our database and with just few tweaks in the Apache server configuration files running this file by opening the browser and typing localhost/contactlist.html would print the records rows into the browser window.
Why few tweaks? Apache comes with default settings of not parsing php code within html files in order for us to be able to parse our php code within the html we need to instruct the server to do so by changing the apache2. conf file found in /etc/apache2/ directory in Debian and Ubuntu Linux distribution or the httpd.conf in some other Linux distro.
If someone tries to run this or any other html code that contain PHP he or she would see unparsed PHP code in the browser window which is indeed very bad and seriously so should such info fall within the prying eyes of hackers in production.
For that reason there are some good suggestions of writing the code which doesn't spell out such important details but fails quickly and involve logging of any error into special chosen output(files/folders) and catching any exception/ errors should one happen on running the code.
We shall discuss a bit on those apache HTTP server settings/configuration in later before winding up this lesson and much more in coming lessons when dealing with integration and deployment.
For the time being let us move on writing the seed_test_data.php file that will be used to populate our database's tables with test data.
Write seed_test_data.php as shown in the following code between <?php and ?>tags and save the file with the given name in bold in the preceding line in the html folder.
<?php require_once("../datadir/Test_Data.php"); require_once("../includes/connection.php"); function cityRecording($db,$cities) { $sql="insert into city(city_name) values(:city_name)"; $stmt=$db->prepare($sql); for($i=0;$i<count($cities);$i++) { $stmt->bindParam(':city_name',$city_name); $city_name=$cities[$i]; $stmt->execute(); } return true; }
function contactRecording($db,$contacts)
{
$sql="insert into contact(name,firstname,email,street,zip_code,cityid) values(?,?,?,?,?,?)";
$stmt=$db->prepare($sql);
for($i=0;$i<count($contacts);$i++)
{
$stmt->execute($contacts[$i]);
}
return true;
}
$conn=new connection();?>
$db=$conn->getConnection();
$location=cityRecording($db,$cities);
$connections=contactRecording($db,$contacts);
if($location&&$connections)
{
echo' Database Initialised Successfully!';
}
Editing Web Server Configuration
Tweaking Apache HTTP server By editing /etc/apache2/apache2.conf if you are using Debian, Ubuntu Linux distro or /etc/apache2/httpd.conf for some other Linux distribution.
Adding the following highlighted text below the last line of apache2.conf file found in the path above:
Addtype application/x-http .php .htm .html .phtml
After that reload apache service by issuing the following command in the terminal. Sudo service apache2 reload
Launch browser visit:
localhost/seed_test_data.php you will see the message "Database Initialised Successfully" If you are connected to internet visiting the localhost/listcontacts.html will render a nice contact page as shown in the next page/slide.
In this case Internet connection will ensure that the foundation.css linked stylesheet file is downloaded by your browser.
This stylesheet will for most time remain within the browser cache for some time unless the cache is cleared so when you visit the localhost shortly later without the internet connection you will still have access to the foundation CSS stylsheet within the browser cache.
Alternatively you may download the foundation CSS stylesheet file and put that file in the html directory of our Address Book project and link its name in the link tag within the head section of your HTML and PHP frontend pages.
Contact Add Form
Launch your text editor open the template.html select it all copy and paste it into another window in the text editor.
Start editing the pasted form as described below.
1.Insert the following code block above the Doctype declaration make sure you start at the top most line leaving no space behind not even a single one.
<?php require_once("../includes/connection.php"); require_once("../utility.php"); require_once("../addContact.php"); ?>
2.Insert the following code between <section> and</section> tags and insert" Add Contact Form" between <title> and </title> tags then save it as addcontact.html file in html directory of our Address Book Project
<form name="addcontact" action="" method="POST">
<label for="name">Name</label>
<input name="name" id="name" type="text" required="true">
<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" type="text" required="true">
<label for="email">Email</label>
<input name="email" id="email" type="email" required="true">
<label for="street">Street</label>
<input name="street" id="street" type="text" required="true">
<label for="zip_code">Zip code</label>
<input name="zip_code" id="zip_code" type="text" required="true">
<label for="cityid">City</label>
<select>
<?php
$conn=new connection(); $db=$conn->getconnection(); $cities=listCities($db); foreach($cities as $city) { $cityid=$city['id']; $city_name=$city['city_name']; echo'<option value='.$cityid.'>'.$city_name.'</option>'; } ?> </select> <input class="button success" name="save" type="submit" value="SAVE"/> <input class="button alert" name="cancel" type="reset" value="CANCEL"/> </form>
Elaborations on Add Contact Forms Functionality
In the addContact.php script put between the <?php and ?> tags at the top of the file if it is not yet there. That will be made in the upcoming lesson about Backend Development engineering, so the full functionality will be brought up after reaching that lesson for now just leave it as that until then.
Additional point: if you would like to have a footer notice well written into that footer section, do not forget to add the following code in bold between <footer> and </footer> tags:
<?php footNoting(); ?>
Edit Contact Form
Launch your text editor open the template.html copy it all. Open another window in the text editor paste it there. Now edit the template by:
1. Inserting the following code above the Doctype declaration at the first line of the document making sure that you leave no space behind not even a single one.
<?php require_once("../includes/connection.php"); require_once("../includes/utility.php"); require_once("../includes/editContact.php"); ?>
2. Changing the title by inserting Contact Edit Form between <title> and </title> tags.
3. Insert the following code between <section> and</section> tags and insert" Add Contact Form" between <title> and </title> tags.
4. Add the following code in bold between <footer> and </footer> tags:
<?php footNoting(); ?>
Remember to save the file as editcontact.php file in html directory of our Address Book Project
<?php $conn=new connection(); $db=$conn->getconnection(); $contactid=isset($_GET['id'])?$_GET['id']:null; if($contactid!=null) { $contact=getContactById($db,$contactid); $name=$contact[0]['name']; $firstname=$contact[0]['firstname']; $email=$contact[0]['email']; $street=$contact[0]['street']; $zip_code=$contact[0]['zip_code']; $cityid=$contact[0]['cityid']; $city=$contact[0]['city_name']; echo '<form name="editcontact" action="" method="POST">'; echo '<label for="name">Name</label>'; echo '<input name="name" id="name" type="text" value="'.$name.'" required="true">'; echo '<label for="firstname">Firstname</label>'; echo '<input name="firstname" id="firstname" type="text" value='.$firstname.' required="true">'; echo '<label for="email">Email</label>'; echo '<input name="email" id="email" type="email" value='.$email.' required="true">'; echo '<label for="street">Street</label>'; echo '<input name="street" id="street" type="text" value='.$street.' required="true">'; echo '<label for="zip_code">Zip code</label>'; echo '<input name="zip_code" id="zip_code" type="text" value='.$zip_code.' required="true">'; echo '<label for="cityid">City</label>'; echo'<select>'; $cities=listCities($db); foreach($cities as $newcity) { $city_id=$newcity['id']; if ($city_id!=$cityid) { $city_name=$newcity['city_name']; echo '<option value='.$city_id.'>'.$city_name.'</option>'; } echo '<option value='.$cityid.' selected="true">'.$city.'</option>'; } echo '</select>'; echo '<input class="button success" name="save" type="submit" value="SAVE"/>'; echo "\t"; echo '<input class="button alert" name="cancel" type="reset" value="CANCEL"/>'; echo'</form>'; } else { echo ' ERROR! SOMETHING JUST WENT WRONG PLEASE RETRY OR IF THE ERROR PERSIST CONTACT THE ADMINSTRATOR'; } ?>
Closing Notes
Trying to run the remaining pages (editcontact.html and addcontact.html won’t execute as expected until we complete adding the two server-side logic files (editContact.php and addContact.php) in the include folder of our address book project and that will be done in the next lesson on Backend Development.
Backend Development
In this lesson we are going to make two PHP files named addContact.php and editContact.php.
Each of those files deals with the server-side logic associated with their corresponding frontend files; addcontact.html and editcontact.php respectively.
The main server side logic functionality performed by each one of this two files has to do with inputs validation and sanitizing these includes for instance making sure that null/empty values are not allowed to pass through .
This security activity is done purposely to ensure that the data that is allowed into the database is valid and conforms to the set standards of metadata.
On doing these security functionalities the condition is that if the data posted to the server fail the test then the expected crud operation is not performed and the server issues the statement requiring the user to correct any mistake noted in the data sent to the server.
On another hand if the data posted to the server is valid and every thing else is OK the expected crud operation will be executed as needed.
With that said it time to start coding for the two files.
Due to the fact that both two files are a bit long to fit precisely within the slides I hereby provide you with the links to download them.
The code for the two files has been commented to some extent to elaborate the logic behind it.
Remember to decompress the downloaded files and save each file with it’s respective name into the includes folder in our address book project folder.
Having added the two files mentioned earlier we can now go and run our address book application by visiting the localhost just by typing localhost/addcontact.html in the browser address bar for add contact functionality and after seeing that performs well we may visit the Contacts List through clicking the Contacts List menu button and go forward to edit contact page functionality for any contact among the list for whom we would like to edit the contact details by clicking the corresponding edit button for that particular contact in a given record row.
By now each of our three pages should be running as supposedly. With keen eye you may have observed that with exception of the listcontacts.html pages our other two pages (addcontact.html and editcontact.php) do not look such great but why this?
The answer to that is in the applied styles, in the listcontacts.html we used the CSS file from foundation.org just as link tag in the head section of the listcontact.html indicates.
Foundation is one of the frontends presentational css library frameworks project that comes packed with a lot of css and JavaScript functionalities in them to easy the development of modern day responsive web design "RWD" which makes sites look good in array of devices from small screen hand-held through medium tablets to the large/wide screen devices out there.
Another popular css framework similar to foundation is Bootstrap. RWD is big subject to be explained in this tutorial.
For further lessons on design get the book "Jump-Start Responsive Web Design" by Chris Ward.
To avail you with good design of the two pages mentioned above you may go to the downloads links given below both of which contain the modified html code that makes use of foundation’s CSS classes to produce state of the art design pages.
After downloading the two files go to the html folder of our address book project delete the previous un modified version of addcontact.html and editcontact.php uncompress each of the two downloaded files and put them in the html folder of our project as replacement to the deleted ones.
Running our address book application through the browser will generate amazing looking pages as shown in the next two pages/slides.
What is Next?
As you may know we once talked about the integration and deployment issue as one of the mile stone in our project.
Having our project running on our on local development machine is just the beginning.
The ultimately goal of Web development project is indeed having the website running 24/7 in a well conditioned production environment whether within the company’s own in house strong server rooms or data centers or from the outsourced well managed IT services company anywhere throughout the globe.
Integration and Deployment are indeed such big topics that may require books of their own. For these topics and many more improvements, features add requests such as using AJAX, Simple or Advanced Search and Pagination.
Please keep it here when series of brief and well documented tutorials like this plus illustrative video tutorials links will be brought to you.
In your own good time you may use the references given within this tutorial for consolidating the knowledge acquired in this tutorial.
The author of this tutorial welcomes any question about the topics discussed in here. For any comments, suggestions or queries finds the author’s contact details attached at the end of this tutorial.
About the Author
Benedict Daniel Masimbani is a full stack developer currently working as an IT consultant with mnadan group.
He is Computer Science graduate from the Institute of Finance Management(IFM) in Dar es Salaam Tanzania.
He has hands on experience in information systems analysis, design, implementation and maintenance across variety of environments and platforms.
Immediately after finishing the third year of computer science degree studies at IFM Benedict underwent internship with Buni Innovation Hub which is under the Development and Technology Transfer Directorate of Tanzania Commission of Science and Technology (COSTECH) at the commission’s Head offices at Kijitonyama area of Kinondoni Disctrict in Dar es Salaam city of the United Republic of Tanzania.
He has served in various capacities in the production of www.mnadan.co.tz and sister site www.mnadan.com both of which are owned by mnadan group since the project inception.
Besides professional life Benedict is a football fan and likes very much to watch competitive football league matches both at home(Tanzania) and abroad plus international tournaments.
You may contact Benedict through his LinkedIn account. You may also get more information about him by visiting his web site.
You need to be a registered user or login to post a comment
1,616,117 PHP developers registered to the PHP Classes site.
Be One of Us!
Login Immediately with your account on:
Comments:
No comments were submitted yet.