Writing A Web App using HTML, PHP and MySQL Introduction Basic ...

94
Writing A Web App using HTML, PHP and MySQL by Ben Allweiss © 2017 Introduction I had been contemplating how to prepare a way to teach programming, but didn’t want to end up with ways to create different bits of code one might as well find searching the web. Then it struck me how I learned my first programming language for PC’s 35 years ago called dBase II. It was one of the first programming languages for micro computer applications. It was great book that taught Databases, and Applications, using an accounting program as the example application. You got a great billing program, and learned by example how to code given an accounting problem, and the syntax of the dBase language. It was learning by example. In this book, and code example, you are going to learn how to write an accounting application, using programming tools commonly applied to Web Based database applications. We are going to create a sample Payroll web site, and develop it using HTML, PHP and MySQL. These are two Web Development languages, and a database tool and language that are commonly used, and free. Basic Elements in Starting the Payroll Web App You can start development of your sample application the following way. First, you will either decide on, or be assigned (either by your instructor or employer), the type of program you are going to code. You will need a complete idea of the input, and outputs of your program, as well as how it will need to function internally. For this example, we will be developing a samplel program called WebPay. It is a Web APP that would be used in a small business, that has either a bookkeeper or accountant prepare their payroll. The APP is maintained on a cloud server with PHP, and a MySQL database. The APP provided is meant as a full example of one that you might want to make. However the purpose of WebPay is as an aid to this book. It’s use is not meant as a commercial program to be used in an active company. However, it has many features of a payroll APP that is. Each year, you need to create a new subdirectory/database of the server as the APP itself only manages data for a single year. Being on the cloud makes it possible to access the APP anywhere on the Web. Security is served by having a login feature with User ID and Password. You need to know information about the employees, the payroll tax law, and the output you need. Output will be the period end paychecks, and tax and pay reports. You need to know the output for weekly, monthly, quarterly and yearly reports for tax returns. These are covered in more detail below. However, you should know all these requirements BEFORE you start planning and coding. Please note also that PHP and MySQL APP’s can be developed on both Windows and Linux systems. Usually, however, the finished APP is run on Linux/Unix servers. Get PHP and

Transcript of Writing A Web App using HTML, PHP and MySQL Introduction Basic ...

Writing A Web App

using HTML, PHP and MySQL

by Ben Allweiss © 2017

Introduction

I had been contemplating how to prepare a way to teach programming, but didn’t want to end up with ways to create different

bits of code one might as well find searching the web. Then it struck me how I learned my first programming language for PC’s 35

years ago called dBase II.

It was one of the first programming languages for micro computer applications. It was great book that taught Databases, and

Applications, using an accounting program as the example application. You got a great billing program, and learned by example

how to code given an accounting problem, and the syntax of the dBase language.

It was learning by example.

In this book, and code example, you are going to learn how to write an accounting application, using programming tools

commonly applied to Web Based database applications. We are going to create a sample Payroll web site, and develop it using

HTML, PHP and MySQL. These are two Web Development languages, and a database tool and language that are commonly used,

and free.

Basic Elements in Starting the Payroll Web App

You can start development of your sample application the following way. First, you will either decide on, or be assigned (either by

your instructor or employer), the type of program you are going to code. You will need a complete idea of the input, and outputs

of your program, as well as how it will need to function internally.

For this example, we will be developing a samplel program called WebPay. It is a Web APP that would be used in a small business,

that has either a bookkeeper or accountant prepare their payroll. The APP is maintained on a cloud server with PHP, and a MySQL

database. The APP provided is meant as a full example of one that you might want to make. However the purpose of WebPay is

as an aid to this book. It’s use is not meant as a commercial program to be used in an active company. However, it has many

features of a payroll APP that is. Each year, you need to create a new subdirectory/database of the server as the APP itself only

manages data for a single year. Being on the cloud makes it possible to access the APP anywhere on the Web. Security is served

by having a login feature with User ID and Password. You need to know information about the employees, the payroll tax law,

and the output you need. Output will be the period end paychecks, and tax and pay reports. You need to know the output for

weekly, monthly, quarterly and yearly reports for tax returns. These are covered in more detail below. However, you should

know all these requirements BEFORE you start planning and coding. Please note also that PHP and MySQL APP’s can be

developed on both Windows and Linux systems. Usually, however, the finished APP is run on Linux/Unix servers. Get PHP and

MySQL for your development environment from http://php.net/downloads.php and https://dev.mysql.com/downloads/windows/

. Use the current stable versions. (PHP 5.6.31 and for Windows the MySQL Installer). Read the directions on these sites.

WebPay was written on Windows 7 Pro.

Next, you need to work out the programs forms, which will be used in entering data according to the rules of the application.

Forms also let you specify the output of the app in the different reports. These will be given in detail below for the payroll app.

While reviewing the type of program you will be working on, you should also be thinking about the database structure that will

work well for you. You can use this example to help you understand how a database works in making a program work well.

You can only do one thing at a time, but you must create, and use, the following in different and combined steps. The steps are

as follows, as you flow through the development process:

* Define and understand what you are trying to automate (in this example “Small Business Payroll Application”)

* Understand the data you need to store in the database.

* Design the forms you need to enter data into, get reports from, and maintain the website.

Understanding the application

You are learning to write a simple Web Based Payroll application for a small business. So we must first outline the Payroll process.

This will make it so we can create the complete code of the details involved. We will use a description which is somewhat general,

but the complete detail will be included later, which has to be done in the actual coding. This description will guide us as to how

the program needs to be formed.

The Payroll Process:

How to create a payroll using the following information, and calculations.

* Salary

* Rate

* FICA tax equations.

* Medicare Tax equation.

* Federal Tax Withholding Tables and calculations.

* State Tax Calculation.

* Deductions.

* Marital Status

* Exemptions

* Pay Frequency

* Paydate

Some of this information is maintained in separate tables and doesn’t have to be entered every payroll. In fact most of it is.

Basically Salary, Hours and Rate, as well as Paydate and any deductions are the only things entered during the payroll process, and

are put into the Payroll table at the end of the process. The employee data is put in for all the Employees in the employee table,

Other stored information (e.g. Federal Tax Withholding Tables) is used to create the results which go into Payroll results table.

In this payroll program, the payroll process advances one employee at a time. It is NOT a batch process. As each employee’s

information is put in, it is then calculated, changes can be made, and then it advances into the completed payroll file. Reports

allow you to see all the results and information needed, to pay checks, view accounting reports, and pay period taxes.

The output from this information is gathered every Pay Period into the Payroll table, as follows:

* Gross Pay

* SS Tax

* Medicare Tax

* Federal Withholding Tax

* State Tax

* City Tax

* Deductions

* Net Payroll

Later we will discuss how deletion and changing Period, and Payroll information can be fixed.

Here is a chart of what the Payroll Program does to calculate a Payroll:

There is a lot to do at this point. However so as not to cause any confusion, we will start some actual programming by discussing

what Forms, program data tables, and Employee information we need. We will also design the systems Main Page.

Programs Main Page:

The main screen contains an employee listbox, and eight buttons at the bottom, with the following major program functions.

Company - Is used to record/change your company data.

Add Employee - Is to add a new employee.

Edit Employee - Is to edit an existing employee (selected in the listbox).

Payroll - Is to enter a chosen employee payroll for a particular paydate.

Taxes - Is to report/ enter tax information for the various forms of taxes (Brings up entry forms).

Deductions - Enter general types of deduction names, as well as individual employee deductions (e.g. Friend of Court).

Reports - Brings up a list of different reports (e.g. General Ledger Report for a particular period).

Utilities - Such as delete a payroll, or employee.

First we will see how the Main Page, and the Objects that make it up, is created on the Web page developer. All the other Forms

(e.g. Employee, Company, Reports, etc . are called from the Main Page. So it makes sense to start here.) Also, most Forms are

associated with a Data Table (or Tables). So after we create the Main Page, we will show how a Table is made in MySQL.

Expression Web 4 is the HTML, PHP editor used to do the work in this example. Expression Web 4 is a free download from

Microsoft, but is not supported. However since I started with it for this and other projects, and I like it I, have continued using it.

It is still similar in many ways to other current supported products. But you might want to use more current, supported product

like Eclipse, or other editors found on the Web for PHP. I can only say I have found EW4 the easiest and best.

This is how Expression Web looks, and basically works. It has similarities to other editors, so is worth looking at.

Expression Web basically displays the file, selected from the menu on the left, upper corner (prmain.php), in the center window,

here called WebPay. Each item on the Design screen is called an Object. Here, we have some text, some rectangles, a listbox

(center of page and empty), and eight buttons (each of which call a form which has a major role in WebPay). Note that on the

bottom left of the center window are the choices ( Design, Split and Code). Design shows a graphical format of the web page. You

drag and drop objects from this view. Always use an editor with a Design view when programming web pages. You will see

shortly that you can also see and edit the code that creates the page, by clicking the Code option.

There are two other vital windows on the upper right, and lower left site, that you can use in the Design mode. The following

images show the contents of the upper right window of Expression Web.

This portion of the Toolbox offers you what are called HTML Tags, that can be dragged onto the Design screen (web page) you are

working with. In this example, we use <div> to separate and manage different sections of the web page.

You can scroll down the Toolbox to make various Form Controls that can be drawn onto the page. prmain.php has <div>’s, Input

Buttons, Input Text, and a Textbox (not seen) dragged onto the screen.

Below we show a blank screen that has 3 <div>’s on it, and a label and button. The <div>’s just form portions of the web page. A

textbox on the top shows the programs title. And you see one button in the middle of the screen.

These objects are for learning purposes being shown here. All the objects needed for the main screen are shown in the Image of

prmain.php above. What we want to point out here is the methods used to populate a page.

We start with putting the <div>’s on the page. These are seen as rectangles on the screen. There is one filling the whole page,

one at the top of the first <div>, one in the bottom – middle, and then a narrow one for the buttons .

<Div>’s make it easier to place the page’s objects. If you don’t use <div>’s, the positions of the objects interact in confusing ways.

Just as with the objects to follow, <div>’s need to be placed in a certain manner, as follows.

* Drag the first <div> on the screen (which will be blank at first). Then select on the top menu Format - > Position -> Absolute.

* You then need to put your mouse pointer on one of the edges of the <div> rectangle and click it. It will be focused, as is

indicated by some indication points on the corners, and middle of the sides.

* Size the rectangle by dragging the points on the <div>. When the mouse is on the indication points, with horizontal, vertical, or

diagonal dots, the size of the <div> is changed. You move the entire <div> by clicking on the <div> side, and X shaped arrows

show. You then move the <div>, (or other object).

For this example APP, the <div>’s are set up as shown just above.

Now we want to place the Textbox, and a single Button on the screen. They are shown on the figure as follows:

Both the textbox, on the upper left, and the button, were dragged on to their containers <div>’s. Then they were Formatted

Position Absolute. Then they were dragged to the desired place using the mouse pointer.

When you create an object, such as a button, you need to set Attributes. These are, for example, the name of the object, the

value, the style, and the type. These all have default values, but you need to set them to what you want. The lower left side of

Expression Web has a box called Tag Properties. This contains the Attributes for the selected object, in this case a button. See the

figure here:

The next thing to be introduced to is the Code Editor. We get to it by clicking on the Code tab of the editor.

We will start with this example, and later on will look at the prmain.php screen, which contains the complete code.

Look carefully at the code below, paying particular attention to the format of the HTML Tags (within the brackets).

You will notice, the two outmost HTML Tags are <HTML>. This is natural since the basic structure of the code is HTML. This is

even though the code will eventually contain PHP, and some Javascript.

The <head> tag contains page information. The closing tags always have the “/” character, as shown.

Next, the <body> tag contains the main part of the HTML page.

You will also observe the <div> tags. There can be <div>’s within <div>’s. On the Design view we made rectangle <div>’s within

<div>’s.

However they do not appear exactly that way in this sample code! We have not gotten what we wanted exactly, as described

earlier. We want the <div>’s to be nested as follows:

* First <div> is outmost, whole page.

* Second <div> at top, rectangle inside at top of first <div>.

* Third <div> also inside First <div>, below Second <div>.

* Fourth <div> inside Third <div>.

They then look as follows:

Now you see the code has the proper <div> nesting.

You will also note the <form> tag. This is used to control the page processing when the Button’s are pressed. There are also other

objects (textbox’s etc) in the form section. Form lets the page know what needs to be processed. This is shown in working detail

later, when discussing the full main page code.

Finally, note the two <input> tags. The top is used to hold the name of the program. The second (button) performs an action

when pressed. Also, both < input> tags have a name and some values in the style line. The name is used in the actual program to

help process these objects. There can also be an id used, in case you use javascript in your APP. Style helps control the width,

height, type of position (absolute), and position (in pixels from the upper left corner of the appropriate <div> containers, and type

of object (e.g. button or submit).

This gives you a good idea of the basic graphical, and code structure, of an HTML page. Before we look at the actual prmain.php

page, we will now give a short introduction to the MySQL database, and the first table we have created that contains information

accessed by this first page.

MySQL database, and employee table

You work on your database and tables using the MySQL Workbench and PHP code. MySQL and PHP go very well together. We

will look at these two tools, however you should also look at the MySQL web site for how to install and work with the Workbench

in greater detail.

When MySQL is all set up, Workbench is used to create Databases (called SCHEMA in MySQL), and the tables in the database. On

your Windows system, the Workbench will come up as shown above. The thing to notice in this case, is the LOCAL Instance of

MySQL. The user ID is “root”, and the localhost is “3306”. You click the shaded box, and then Connect on the panel that will show

up.

The following login screen will then show up.

Put in your password, which you created when setting up MySQL.

After doing so, the following screen will appear.

We got to this point by first setting up the Schema (webprmast database) and its Tables (employee and company).

See the figure below:

We got the Schema webprmast by clicking on the Add Schema figure at the top of the main screen. This brings up the following

screen, to name the Schema.

Press APPLY at the lower right of the Schema window, and the schema name will appear in the list on the lower left window.

Make sure to click on the Schema name (lower left) so it is the active Schema. You may need to right click on the Schema name,

and click on Make Default Schema on the menu that pops up.

Now your environment looks like this:

The Tables appear after you add them to the empty Table option. The is done by clicking on webprmast - > Tables -> and Add

Table (on the menu that pops up).

Once you add a Table, you have to set up its Columns. Highlighting the employee table, you right click then select Alter Table

from the menu. The following completed table has been created:

The Table is described as follows.

The Schema list on the lower left partially displays the employee structure, with two columns, empno and ssno. The large

window at center, right, shows the Table Name, employee, and in the middle center, the column names, data type for each

column, and some column characteristics, such PK (Primary Key, Not Null).

All of this information, is entered in this same table, which initially is blank. It may be changed after the initial Table creation, and

pressing Apply will execute Alter Table. If you don’t want to alter the Table, just click the X tab at the top of the screen.

Finally, note that you want to Save the database as necessary, to avoid losing data due to error or system failure. To do this, on

the left window, under the Management menu, there is the Data Export and Data Import/Restore options. These will bring up the

following screens, which allow you to Backup and Restore your database.

On this screen, you want to check the Schema containing the Tables to Save. You likely want to export to the Dump Project

Folder. The system will create a Dump Folder with the current date. Just Click Start Export, at the lower right.

To restore the data, bring up the Data Import/Restore screen an click as follows:

Just select Import from Disk - > Import from Dump Project Folder. Click Start Import button on the lower right corner.

Now we will turn to the actual prmain.php web page, with knowledge of the employee Table it uses, so the page can be

understood. There a more tables that are used in the Payroll program, but at this point the employee table is what is needed.

We present the prmain.php file screen to review its structure and function.

The complete main web page is similar to the example we gave at the beginning of this chapter. It contains the program title, a

listbox of the employees, and the buttons to use with the program below the list.

To take things one thing at a time, we start with the main screen, and three program functions (called by buttons) Company, Add

Employee and Edit Employee. These create and process information we need first to create and use the system.

The main screen lets you choose what you want to do, and is the central part of WebPay. Not all the selection buttons require

you to select a particular employee, but the Edit Employee, and Payroll buttons do. Let see how the Main Page is coded.

Here are the first few lines of the main web page. The remaining lines follow in series, with explanations.

The first five lines are created by Expression Web, the HTML editor. They simply set a few tags to run the program. You will note

the <?php tag on line nine. This indicates some PHP code follows in the next lines of code, which are shown below. The end of

PHP code is followed by ?> /* and */ surrounds comments, and // leads a line comment. <!-- --> contains an HTML

comment.

Also, be aware of the BSD License in green. This makes it legal to distribute the program.

This second section of code does the following. First, note that it completes the PHP section of code (line 62) started above.

Line 40 adds the code in ‘dbConnParms.php’ to this file (prmain.php). That code assigns the Connection Parameters, used for

connecting to the MySQL database, to four PHP variables. This code is as follows, and is needed in prmain.php, as you will see in

the code of the connection string.

The ‘session’ code requires a little explanation.

Sometimes you need to pass values between web pages. There are a couple ways to do this, and using a ‘session’ is one way to

do it. When you start a ‘session’ with session_start(), it makes PHP carry variables like $_SESSION[“variable1”] between pages.

You can then use these variables, in any page with session_start() in the beginning. In this program, the employee number is

sometimes needed between pages, so $_SESSION[“session_empno’] is used that way.

The session variables on lines 43 and 45 are used that way, and initialized here.

The function, alertBlankInput, is a PHP function. It is called in the code below. After it, appears ?> which ends this block of PHP

code. We will use <?php and ?> to block off more PHP code throughout this program.

The above section of code is in javascript. While this is mainly and HTML/PHP website, some things are more easily done in

javascript. The ‘on Company’ and ‘onAddEmp’ functions are called by the appropriate buttons on this page. They bring up the

‘company.php’ or ‘addemp.php’ files, which don’t require passing any variables or values. Ignore the onPayroll() function.

This code was created by the Expression Web (EW) editor, by selecting fonts, font sizes, and alignment when text was being typed

onto the Design screen of EW. It is in the <style> section of the page. css stands for ‘Cascading Style Sheet’> The name of each

style is followed by the coded format of each style. The name of the style, for example ‘.auto-style1’ is the class of the associated

tag that is found in the body of the page. In this case, the tags are <div>’s.

The previous two code samples exist in the Payroll program in the order shown, and they function together. The form tag

contains the employee textbox, which can be clicked on, and the input buttons (and submit buttons) that are used to control the

program.

You need to know how a <form> </form> screen works. You have an object, such as a select object (you may also find a textbox in

other cases), to which you either enter data, or in which you select data. You have at least one ‘submit’ button that tells the

program to process the data selected in the select object. At this point in development of the program, if you press ‘bEditEmp’,

after first selecting one employee in the select object, the program will reload the page, and execute the PHP code in the

$_SERVER if statement. This is because the <form> code says that the method = ‘post’, and the $_SERVER is PHP_SELF. This

means executing the form will re-execute the page the post was called from. That is, this page.

Now look at the PHP code sample just above the HTML code sample. It executes if $_SESSION… “POST” . Looking at it carefully,

you will see that it will execute the code for the ‘bEditEmp’ and call the ‘editemp.php file. It also sends the empno in the

$_SESSION[‘session_empno’] variable.

A little more about the <form> code, concerning showing the employee data, and passing it to the PHP code above.

The ‘sometext’ in the ‘name=sometext’ of the <select> tag tells PHP that the variable ‘sometext’ variable is sending the selected

employee number to $_REQUEST[‘sometext’]. This is then passed to $txtmySelectVal which then is passed to

$_SESSION[‘session_empno’].

Another thing to know is how the employee data fills the select object.

This is done in the ‘select’ code.

In a simple format, the textbox appears in code as follows:

However, in this case we need to fill the box with contents of the employee table in the data base. So, in lines two Figs above 241

thru 245, we see code to connect to the webprmast database, and code to select data into the table object $result.

Then, we need to put an option tag into the textbox for each employee in the table. But how to do this?

In lines 253 to 255 we use a while loop and PHP to write an echo line for each option line. Think of it as using PHP code to write

the HTML object, but in a way that PHP can put the employee data in each line. Study the echo command to see how it does this.

Finally, looking at the echo line, you see the option line contains a “value=” value for the empno value. This is the employee

number of the <option> you pick when using the program. That value is assigned to the ‘sometext’ after you click on an

employee line, and then press the submit button bEditEmp. Then the page reloads and the PHP ‘POST’ section is executed.

This technique of using PHP is used throughout the program, and is very useful in many instances. Even in other programs. It lets

you use buttons, textboxes, and other objects in relatively sophisticated ways.

Pay attention to the technique thru out this Web APP.

Now let’s look at the Company, Add Employee and Edit Employee screens to see how we setup this basic information used in

operation of the APP. Since that’s the way it’s used throughout WebPay, you need to enter the information before using it in the

system.

The Company page is brought up by simply by clicking the Company button on the main screen. Let’s see how it looks, is used,

and how it is coded.

The Company Screen has information needed in many parts of the program. Especially in many tax reports. It is accessed from a

button in the lower left hand part of the main screen. Since no data is passed between the main screen and the Company Screen,

the code in the main screen simply calls the Company Screen from a javascript procedure the button on the main screen calls

when clicked.

Here is the code that controls calling of the Company Screen.

Notice the button with the name bCompany in the code. Next notice the “onclick” code it calls.

The onCompany() function calls company.php, which brings up the screen shown.

Next, look at the company page as it looks in Expression Web (HTML Editor):

There are three major types of objects on this page. These are text boxes, labels, and buttons.

We will look at the textboxes first. These are the 3D rectangles at the middle of the screen. Using Expression Web, you can drag

all of these boxes onto the screen. You can click on the boxes after dragging them to give them the desired dimensions. But you

can use a little trick to make this easier, and for a better result.

The trick is to drag on the top textbox, and position and size it. Then go to the code tab on the HTML Editor, and find the HTML

for that textbox. If you first highlight the textbox, it will also be highlighted on the code. This is as follows:

Note the highlighted textbox. Then this appears in the code:

Now… Instead of dragging all of the remaining boxes and sizing them on the screen, you can copy the code and customize each

line, and you will get perfectly placed boxes on the screen. The only thing you have to do regarding placement, is change the

“top:” style parameter to place the box in the correct vertical position on the page.

We will come back to the textboxes, but first let’s see how the company information is initialized in these boxes when calling the

screen. This information goes into the “value:” parameter of the boxes.

Here is the code that gets the company information from the company table at the top of the company screen code:

This code appears at the beginning of the code section in the HTML Editor. On line 76 the $_SESSION[‘isfirst’] test lets the

program know you are bringing up the Company page for the first time. Thus it needs to fill in the textboxes with company data if

you have previously filled it in.

In the first block of the if statement the APP first connects to the database. Then the SQL statement appears, which is used in the

next line of code (line 86) to create what is called a cursor, which is just a table satisfying the conditions in the SQL SELECT

statement. Continuing with line 86, $conn indicates the connection the query($sql) is working with. The $result object is what we

have to work with regarding the company table.

If there is a record in the company table ($result object) we continue on in the code, assigning the various $txtBOX variables the

fields in the $result object. These are accessed using the $row[‘field’] objects’, the $row object getting its values from the $row =

$result->fetch->assoc(); statement.

If there is no record in company, the row count will be 0, and the $txtvariables will just be set to blanks. This must be done, or the

calls to these variables in the HTML code will cause ‘missing variables’ errors.

Once that company values show up on the page, the user can either just quit the page, or make changes and then press Save. If

the user Quits, the APP just goes to the onQuit() function at the top of the code, which just sends you back to the main page of

the APP. The button code, and the function that does this follows:

This is the onQuit() code.

This is the Save and Quit code.

There is something about the button types that needs to be understood before we go on, as it applies throughout the APP. If you

want to use the onclick procedure, as with the Quit button, you need to make the type= a “button” assignment. Then you can

call a javascript onclick function as is done here. This is done in this APP when you don’t need to pass variables, and just need to

call another file.

If you need to pass textbox values and other information (as with a select list) on the page to PHP code on this page (discussed

next), type must be set to “submit”. How you do this on this, and other pages, is done next when we discuss the “Save” action.

When you click the Save button, you are pressing a button of type=”submit”. Any button of type “submit” processes the

information submitted by the <form> HTML code. This code is shown below:

In the top section of this form, you simply see some <label> tags. These have the labels that appear next to the text boxes on the

form. Below these, you see 10 <input tags>, which are the 10 text boxes in the form. Each input tag is named, for example

“txtCompany”, and hold text which is defined in the “value=” parameter. I have defined each value using PHP, and a PHP variable,

which always begins in a $, and which gets its value at the top of this pages code, as well as when the user changes it.

So, the user has entered the Company name and other information. When Save is clicked, the job of the APP is to save the

information into the Company table in the database.

Since the Save button is of type “submit”, when it is pressed, it will send processing to the “POST” location which exists in the

<form> tag at the top of the form code. On line 287 above, the method is called “post”, and the $_SERVER is called “PHP_SELF”.

PHP_SELF sends processing to this page (the current page). This is in contrast to some (or many) programs which use action/

method (with a file to call, and method=’ GET’), to send processing to another page (with the passing of variables that show up in

the URL called). The method used in this APP make it easier to process a lot of variables. It sends it to the

$_SERVER[“REQUEST_METHOD”] above. This is shown in the middle of the code on this same page (line 125):

Now that we are at this location, we are ready to look at the PHP code to save the page data line by line!

After line 125, which execution brings execution to, you see many PHP variables being assigned values. The first line, number

128, assigns the button a value. You will see later, that this value tells the APP that the Save button has been pressed.

Below that, you see the assignment the multiple textbox values to PHP variable values. For example txtCompany to

$txtCompanyVal. This is done so below, we can assign the new company values, to the Company table field values. This is done

as follows:

On line 165, the if statement tests if the Save button has been pressed by looking if it is empty. It is not, so it will execute the code

after else. Next we create the connection to the database, which contains all of the APP’s tables.

That being done, we set and execute the SQL statement. In this case, we are just testing for a record in the company table. Now,

the company table should have no more than one record in it. If that record is already there, we just want to UPDATE the table.

This UPDATE, and the SQL statement for it, is executed if there is a record in the table. This should be the case for any case after

the first save of Company information. Read from line 177 to 198 to see how this is done.

If this is the first time Saving the information, we need to INSERT the data. This is shown below. The INSERT SQL statement

ADD’s records to a table. We only need to do that this first time!

After the INSERT, we close the connection, and then have a bit of javascript which then puts us back on the prmain.php page. See

lines 240 thru 246 on how this is done. Note that on line 240, we end PHP code, and at line 246 we pick back upon it. Also note

the <script> tags on 242 and 244. This way we can use javacode easily within the PHP code.

Note also, we are done executing the Save submit button code. On the same page!

That pretty much finishes it for our company screen. WebPay will use the information in various program and tax reports.

The next thing we need in doing payroll, as well as in reports, is basic employee information. We don’t want to have to re-enter

basic employee information every time we do payroll or print a report. So if we want to store employee name, address, as well as

some information such as marital status, and number of extensions, we need to enter that information.

The buttons that let you get to the employee add and edit screen are shown on the main screen as shown here:

We need to have two ways to enter employee information. One is to add a new employee. The other is to edit an existing

employee. This is because each of these have to be handled a little differently.

Adding an employee requires you to come up with a blank screen, enter the information, and save it. Editing requires you to first

pick an employee, bring of the screen with that information, change the information, and then save it.

Lets see how Add Employee is coded:

First, see that the screen brings up no data. We are adding a new employee. Note that there also is drop down controls. These

are initialized with specific values. Now, lets look at the HTML of the form:

Note in the <input> textbox’s, we only name them, which is needed to save the box values into PHP variables when the save

button is pressed. When we get to the Edit Employee screen, we need to put a value into the <input> boxes. Note also how the

drop down boxes get their values, and send their selected results to PHP.

The PHP code is executed here, in a way similar to that in the Company when it was saved. It executes in this same page, in the

POST section. The <input> objects carry their values to the PHP variables, which are used to INSERT the employee information

into a new record of the employee file.

This code shows how it is done:

Here the textbox objects are being assigned to the PHP variables.

Here we have PHP checking for SSNO duplicates.

Next, we get a new employee ID number, and then INSERT the new record, with values, into the employee table.

Now we look at the Edit Employee screen. We need this feature because employee information may change as time passes. The

main difference is that when the screen is brought up, you have to bring up an existing employee’s data. This is similar to bringing

up Company data in that screen, but you have to select the employee on the main screen employee list, before you press the edit

employee button. If you press that button without highlighting an employee, you will get a “Cannot Process Blank” error box.

This is the PHP code in the editemp.php file, that loads the selected employee data:

The rows in the employee table are assigned to the PHP variables, which we will see in the next code sample, show up in the

screen text boxes.

Note the names of the textboxes <input>, as well as the values assigned from the PHP variables set just above in code.

Also, there are some different types of objects on this page, which have to be set. These are drop down, and select objects. Note

the formatting of their code. It’s a little more complicated than this however. We need to set the values of these drop downs,

and also for two check boxes, not yet shown, before we are done.

We have to use javascript to set these drop boxes to the values obtained in the employee table above.

We see three blocks of code. Each one sets a javascript variable to a PHP variable assigned an employee table column above on

this page. Then, a javascript variable called ‘element’ is assigned to an <input> object. The object is found by using it’s ID value.

There are three id’s found in the Status, Exemption, and PayFreq objects shown in the HTML above. Do not mix them up with the

objects names.

After the element is found, it is assigned the value, such as “element.value = dfltPayFreq”. That is how the values in the employee

table are assigned to these special controls.

In a similar way, the checkbox controls are set on the screen. See next code:

This is done where we got the employee table values.

This is in the body of the HTML code, and is in javascript. It sets the page checkboxes according to the data retrieved from the

employee table.

Having changed the employee information as needed, the user saves it by pressing the save button. This is done much like the

add screen, but instead of inserting a new employee record, we UPDATE the one we are editing. This is shown in code as follows:

Note in the UPDATE SQL code, that at the lines end, the WHERE code includes: empno=".$_SESSION["session_empno"] .

This insures the update only includes the current employee being edited!

Now… with the employee information in the system, we have about half of what we need to compute an employee pay record.

We also need tax information and tables the system uses to calculate Social Security, Medicare, Federal Withholding, and State

Withholding results.

You will see how this information is implemented in WebPay. But to better understand it, we will first see how it all goes together

by showing how the system processes an employee pay record from start to finish.

First, look at this explanation from IRS Circular E to see how it is done manually. Then we will show how the process occurs in

WebPay, and how it is coded.

WebPay uses Federal and State Tax information to calculate taxes automatically. The only extra work that is needed to do this is

to enter some numbers into the APP’s tables, since that data usually changes every year. But it only takes two to three hours to

transfer the data from IRS and State tables.

To do federal taxes, we only need to take Gross Wages and deduct the number of federal exemptions times the exemption

amount. Then take the result, and use the Federal Percentage Tables to get the amount to withhold. Note that WebPay only uses

Weekly thru Monthly pay periods.

Knowing this, you only need to enter the table data into eight tables, altogether, and the exemption amounts for the payroll

periods. Those screens are under the Taxes section of the APP, one of which I show here:

For the flat State Withholding Tax (the only type WebPay can handle at this time), you only need the following (for Michigan):

Note that you need to also enter government supplied data on Social Security and Medicare, as well as numbers on Federal and

State Unemployment.

Use care in entering this data, as errors will cause problems with your payroll calculations and reports.

Again, these numbers must be updated every year!

Now let’s see how we process an employee, and the how it is coded in PHP!

First, we bring up the main screen, select the employee we want to process, and then work the two screens that are used in doing

the task!

This is the main screen, with an employee highlighted:

The first step in processing an employee’s payroll is to select the employee from the main screen list, and clicking the Payroll

button:

This action is processed in prmain.php code as follows.

First, selecting the employee in the list works like this:

The <select> and <form> objects pass the employee number to the Payroll button processing on this same page.

Note that on line 276, the code specifies that the value of the option, when pressed is equal to $row[‘empno’]. The specific value

is the one of the highlighted line on the actual screen.

When Payroll is then clicked on, this empno value is passed to the following code:

The code on line 149 passes the correct empno (in ‘sometext’ from the <select> HTML code above) to the PHP variable

$txtmySelectVal. This value is then used when we call payroll.php (the first payroll screen of two used in processing) as is shown

now:

Line 186 assigns the PHP empno value to the session variable $_SESSION[“session_empno”] (often used to pass variables between

pages in this APP) so it can be called in the payroll.php page. Then line 199 has code calling the payroll.php file. Note we use

javascript to do this call.

The payroll screen comes up looking like this:

This page is brought up in a manner similar to the Edit Employee screen talked about earlier. There are some differences

however, in future use. First, the user must make sure the Paydate is for the current Paydate, and also put in any wage, rate and

work hours data for the current pay of this employee. Also, any deduction numbers must be put in.

You must also note that numbers may already be set if they were already known. In this case Salary is $800 for example, and

probably need not be changed. These numbers may be changed, however.

In code, values of the textboxes may be inserted as follows. This includes the special dropdown boxes.

The code at the top of payroll.php follows:

On line 58 we first get a variable $txtPayDate. This is from a table called vars. Vars is a one record table used to hold values in the

APP, which are passed to screens in WebPay. It also holds some tax values, such as Federal and State Exemption values, among

others that will show up later.

Then, using the same connection, we get the deduction names which show up on the first Payroll page, from the dednames table.

Next, we get the deduction values from the empdedns table, which holds values you might need to deduct (such as Friend of

Court, or Employee Advance), every pay period. But these can be changed while doing the payroll.

Note that you use a ! as first character of a deduction name, if it is non-taxable. These category deductions are not included in

Box 1 of W2 and W3.

Finally, below, we see employee information. You either use all the transferred data, or you can enter and change some

information. For example Salary, or Regular Hours, or a Deduction. There are also two PHP variables set from the employee

table, called whFed, and whState, which were set in the ADD Employee/EDIT Employee screens. These determine if the Fed/State

Withholding taxes will be deducted. This is seen in code, below.

After making any changes desired, the user presses CALC. This will compute all wages and taxes on this employee, and transfer

them to the record in the vars table. Then the verify page will come up, and you will see the pay record ready to POST in the

payroll (final posting) table.

But let’s first see how this page (payroll.php) calculates the payroll. Then we will examine the verify page.

This is how some of the PHP variables get their value when the payroll.php screen is saved:

This code works like the code in the two employee screens covered in the ADD/EDIT employee portion of WebPay. That is, it

assigns the screen objects by name to PHP variables.

Next we see code and comments that tells us where we are with the wage PHP variables, and calculations:

The variables that were created above from the screen objects are commented on for tracking purposes. The regwages and

otwages are created at the bottom (lines 351 and 354).

The next numbers we need are for Social Security, Medicare, and withholding tax calculation. They are located in the vars table

record. How they got there is covered later, when the tax number entry is covered. For now, we just look how we get, and use

them at this point.

You can see how the Social Security Percent and Limit, as well as that for the Medicare, are assigned to PHP variables. The

exemption values for Federal and State taxes are retrieved below them. Limits indicate wages, above which taxes are not

deducted, are taken. Exemptions exist because as wage periods and values change, taxes are treated differently. Note that

Federal Withholding is graduated (the more you make, the higher the tax rate). State Withholding is a flat tax in WebPay.

Now we look at how Social Security and Medicare taxes are subtracted from the current employee:

The way the Social Security is calculated is as follows.

Social Security is paid on wages up to, and including the SS Limit. After that, no Social Security is deducted. Review the PHP code

above to see it does this.

Medicare is calculated the same way. In the field, however, it is calculated on all wages. So the Medicare Limit is set as

$999999.99

Medicare is calculated:

Next, we have to compute Federal Withholding Tax. This involves multiple deduction percentages, and so uses Percentage

Withholding Tables.

Before going to the tables, however, we have to adjust gross wages by marital status and pay frequency, as well as number of

exemptions. Then we can go to the Federal Percentage Tables.

Recall the IRS Circular E figure showing how the Federal Withholding tax is calculated. This code does the same thing. First, using

the number of exemptions, the marital status, and the pay frequency, the SQL SELECT statement finds the rules in the FWTPCT

table for handling this employee. The BASE, Percent, and XSOVER is used in the formula at the bottom for getting the Federal

Withholding. It is the BASE, plus the percent value times the (adjusted gross amount less the excess over value).

If this employee is marked not to withhold federal withholding tax, the $txtFWYVal is set to zero (not shown).

If there is a deduction not included in taxable wages, FWT is reduced for this period (but wages are only shown reduces in forms

W2/W3 Box 1).

The State Withholding is a flat tax, but involves exemptions, and an exempt value. This is shown in this code. After adjusting the

wage, it is multiplied by the state withholding percentage. That is deducted, unless the user has marked the employee record not

to have state withholding deducted. Remember, if your state does not have a flat income tax, you can’t use WebPay (unless you

put in the state income tax manually on the verify step(next pay step))!

Now that all our payroll numbers have been set, we UPDATE the vars record columns with the numbers to be passed to the

vfypay.php screen. The following code shows this, and the call to vfypay.php

The vfypay.php call brings up the following page:

The verify payroll page comes up so you can verify the current payroll, and make changes in tax or deduction amounts before

posting the record in the payroll table.

Vfypay.php works much like the other screens that load information, let you look at and change it, and then allows you to post the

data. However vfypay.php gets it’s information mainly from the vars table, that got its data from the previous screens

(payroll.php) CALC option.

The following code shows the code that loads information onto the verify page:

This code updates the label names for deductions on the verify page.

The next piece of code gets all the vfypay.php screens information from the vars table, and updates the values to be seen, and

modified if needed. Note that all vars table column names start with a ‘v’. This is done for clarity, and the fact that the table they

are in is the vars table.

As with other screens that present data when loaded, the HTML code contains the PHP variables loaded in their value options.

After verifying the employee pay data, POST is clicked, and the PHP code is executed on this page, in a manner similar to the

previous page. However, here the data is INSERTed into the payroll table. The payroll table holds all of the employee pay records

for permanent storage and reports.

Note that since this is always a new record, this is an INSERT. Also note that last paydate is UPDATED in the vars and employee

tables. This will show up on the main screen list, and when you bring up the next employee payroll screen (first one).

Now that we know how to run a payroll, it remains that you know something about the tax tables, and finally how the reports and

tax forms are coded.

Remember you were shown IRS Circular E, and the screens in WebPay that let you update the tables from it. Here, you will be

shown the FEDPCT table that hold the Federal Percentage Calculation Tables, and how you code the table screens (eight of them)

so you can enter from WebPay.

Here is the FWTPCT percent table as brought up thru MySQL Workbench. Remember, we covered bringing up tables in MySQL

Workbench near the beginning of this text.

Note the column names match those in the APP’s screen. Also, each line is unique in that a given marital status, frequency, and

over/le denote a certain Base, Pct and xsover number. You use these as was covered in the IRS Circular E example seen

previously.

Knowing how this works you would ask, how to get these numbers in the FWTPCT table. The code that follows shows how.

The screen must first get the existing numbers like any other screen. But note here that a different/unique row in the fwtpct table

must be loaded into each screen line (of textboxes). This is done by using the where clause in each SELECT statement, and

uniquely selecting each line. This ends up with a screen looking like the matching rows in the table.

For different screens, but using the same fwtpct table in MySQL, we fill other screens this same way, using different sm (for

single/married, 1 or 2) and freq (weekly, biweekly, semimonthly, monthly or 1,2,3,4) numbers. This means 8 different types of

screens from one MySQL table.

To save these numbers if you change them (likely at beginning of the year), the following code is used:

For each line in the given screen, we update the matching fwtpct line. This is done using UPDATE, with the associated WHERE

clause. The are eight lines, so there are a lot of updates! And this is done for eight screens.

Next we consider the code for the exemption tables. This data is held in the vars table, in a single record.

This is how the federal exemption screen looks in the Design screen of Expression Web. Note which tax values are managed using

this page.

The next code shows how the screen is populated from the vars table.

Note this is done in the same manner table values have been assigned to PHP variables in previously covered screens.

After these values have been edited, usually at begin of year, they can be saved as follows:

The vars record always exists. So it is just updated. Then we just go to taxes.php

The state exemption values are handled almost the same as the federal. You can look at the txstexempt.php file to see it for

yourself.

WebPay Reports

We have now seen how employees are entered into the system, how needed tax information is managed, and how an employee

payroll is done. We will now look at some system reports are used, what they say, and how they are coded.

The Report screen offers several reports for viewing. We will cover Print Employee Stubs, which shows payday information for

the employee. General Ledger is generally used in making the Payroll entry in monthly accounting. And Income Summary, which

gives pay information in detail form for the selected period.

Let’s first look at the Employee Stub. You will see for Reports, that all data already exists in the system tables that are needed to

produce the reports. This includes the payroll table, as well as the others.

Here you see the Reports main screen that shows all the general reports available. Note that the center row of buttons are based

on the Period Dropdown, which gives the time period the reports are based on. The Stubs and Paycards are not based on this

Period.

This screen has the following code which calls the various reports.

First we see how the HTML is coded for the objects on the page:

You see the <select> tag which gives the options for the period of the report. Then you see the <submit> buttons, which call the

POST section to pull up the Report file desired.

Here is the PHP code that calls the Reports:

First we get the button that was pressed. This type of coding was show earlier.

Then we process the button. As was shown before:

You see that this code is executed because $btnIncSmyVal was passed. Then, two $_SESSION variables are assigned. These are

used in the Income Summary Report. Then, the report itself is called in javasscript.

Now, we call the Income Summary Report. This report shows total wage and tax, as well as deductions and net pay for the pay

period selected on the Reports selection screen.

Here is how the Income Summary Report is coded.

First, a SQL Select query is coded. Then, the Result of the query feeds the <HTML> list.

Here is the SELECT SQL query:

On line 61 see the sql query. Note, a different SQL statement is used for each kind of period, Q1 – Q4, Month and Year (some not

shown).

Now we execute the SQL statement, and display the Summary:

Note that we execute the query (line 164), and loop thru the result in a while loop.

The end of the while loop is as follows:

Note also there is some formatting so that the list lines up and is easy to read

Now let’s do the employee stub. The Stub looks like this:

The employee stub is of a single payroll table record, for a single pay period. It is chosen on the select screen, for the employee

and the desired pay period. The select screen passes the empno and period.

As you might expect, all we have to do is create an SQL Select statement with those parameters, query the payroll table, and

display the results to the screen.

The code is as follows:

The code above shows how the pay record is retrieved, and the PHP variables created.

Then, we just have to just format and display the variables. You can print the report for the employee by printing the web page

using the browser.

We code for the display of the Employee Stub by using an HTML table. We have to format the table by entering the CSS code in

the <style> section of the HTML code.

Once this is done, we enter the <table> code as follows. This will produce a nice aligned output on the screen, which can be

printed for the employee.

Next your accountant will probably be happy if he see’s you can print out a general ledger payroll report for her monthly work.

WebPay does this, and the report looks as follows:

This report is called from the Reports screen, and gets it’s period covered from the Reports screen, just like the Income Summary

reports.

Like the Pay Stub, you use an SQL Statement to get payroll numbers from the payroll table, and then use HTML/PHP <table> to

display the G/L Report on the browser.

Here is the SQL statement:

Note here that all records in a period month are selected.

This code gets the PHP variables from the payroll table:

And the code below displays the G/L Report to the browser to view or print.

Please note two things in using an HTML table. First, as in the Employee Stub report you need to include the table formatting

code in the style section of the code. Secondly, the table code itself needs to be in the <body> section of the page code. In this

example, specifically in the <form> section of the code. See the rptgl.php source code for complete details.

The final report we will review in this text is the Period Taxes report, which shows the 941 and state taxes you need to pay after

each payroll. (This depends on the size of your payroll, but you can use it either way).

This report is brought up on the Taxes menu, which brings up a period Select screen, which brings up the report. The select

screen, and report looks like this:

The 941 Tax Due select screen works like this.

This is how the Paydate dropdown is coded:

It fills in the dropdown box.

Once you have selected the period you want to see 941 taxes for, you press the View Tax Period button, and the following code is

executed:

You see on lines 91 and 94, the period desired is passed, and the txperrpt.php is called.

The tax report itself is coded as follows.

AN SQL Statement is coded to bring up FICA/MED and Federal Tax for payroll records with the Paydate selected. It looks like this:

Note in the SELECT that the sum of records for a single paydate is computed.

Next we see formatting of variables. This formatting worked fairly well, but you may want to change the way this is done in your

work.

Finally, this is how the report is printed in your browse using the PHP print statement:

Note we use the PHP print command for this Tax report. This is easier that using the HTML <table>, but not always as attractive.

This concludes the guided treatment of the WebPay Reports. There are over a dozen Tax and General Reports in the APP. Many

work in similar manners to those covered. However, you can learn even more by looking at the complete files in the APP, which

you can download from dndlearning.com/macademysw/webpay2017.zip where you can find the complete code of all files.

Conclusion

This text has been written, and a real APP has been developed, to give an in depth example to you on how to write you own real

world APP. You might do that for an employer, for your own customer, or as a developer for whatever reason you may have.

In any event, as in depth as this text/example is, as with everything else in computing, you will always be challenged with the

learning process. But the more you do it, the better you will get.

Some additional aids to your programming efforts can be found in w3schools.com, php.com and dev.mysql.com

Another place to look for help is stackoverflow.com and keyword searches on google.com

A final programming hint is to reuse your own code in a project. Many times code in something you have done in the past can be

used in the current part of the project. By using cut and paste, you can save a lot of time and effort. If you are writing a complete

APP, it is good to write a manual with a good word processor.

It is hoped, as has been the author’s case for over 35 years, that this real world example will help you with your ongoing effort to

improve your skill in PHP, MySQL. It may also help you in any other languages you may use in your programming efforts!