BookPDF Available

TCC 242/05 Web Database Application

Authors:

Abstract and Figures

TCC242/05 Web Database Applications course focuses on the theory and application of server-side development tools used to develop dynamic database-driven web applications. The course will introduce students to then Linux, Apache, MySQL and PHP architecture commonly known as LAMP. PHP is a widely used server side scripting language which will run on an Apache web server hosted on a server powered by the Linux operating system. MySQL is a versatile as well as powerful database engine which is among the favourites for any database-driven web application. The LAMP architecture is quite unique as it is completely Free and Open Source (FOSS). By the end of this course the students would be able to setup Apache web servers, MySQL servers and design complex applications which would harness the full potential of the database-driven approach.
Content may be subject to copyright.
iUNIT 1
Introduction to web development and PHP
TCC 242/05
Web Database Application
Introduction to
Web Development
and PHP
Unit 1
ii WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
COURSE TEAM
Course Team Coordinator: Mr. Ishan Sudeera Abeywardena
Content Writer: Mr. Tang Chun Chong
Instructional Designer: Mr. Yeap Hock Aun
Academic Member: Mr. Chandarasageran Natarajan
COURSE COORDINATOR
Mr. Ishan Sudeera Abeywardena
EXTERNAL COURSE ASSESSOR
Dr. Sanjay Jasola, Gautam Buddha University
PRODUCTION
In-house Editor: Mr. Yeap Hock Aun
Graphic Designer: Ms. Leong Yin Ling
Wawasan Open University is Malaysia’s first private not-for-profit tertiary institution dedicated to
adult learners. It is funded by the Wawasan Education Foundation, a tax-exempt entity established
by the Malaysian People’s Movement Party (Gerakan) and supported by the Yeap Chor Ee Charitable
and Endowment Trusts, other charities, corporations, members of the public and occasional grants
from the Government of Malaysia.
The course material development of the university is funded by Yeap Chor Ee Charitable and
Endowment Trusts.
BY SA
© 2011 Wawasan Open University. Except where otherwise noted, this work is licensed under
the terms of the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view
a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to
Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
This course material was published to support the learning of students registered with
Wawasan Open University. Wawasan Open University does not grant any degree, certification
or credits based solely on your completion of this course material.
Wawasan Open University
Jalan Sultan Ahmad Shah,
10050 Penang.
Tel: (604) 2180333 Fax: (604) 2279214
Email: enquiry@wou.edu.my
Website: www.wou.edu.my
iiiUNIT 1
Introduction to web development and PHP
Contents
Unit 1 Introduction to Web
Development and PHP
Course overview
Unit overview
Unit objectives
1.1 Understanding web development
Objectives
Introduction
Web development A brief description
Methodologies for web development
Databases on the Web
Suggested answers to activities
1.2 Installing and configuring Apache, MySQL
and PHP
Objectives
Introduction
Installing LAMP
Testing the configurations of Apache, PHP and MySQL
Suggested answers to activities
1
3
3
5
5
5
5
8
16
20
23
23
23
23
26
35
iv WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
1.3 Creating basic PHP scripts
Objectives
Introduction
Overview of PHP syntax
Creating your first web page with PHP
Suggested answers to activity
Summary of Unit 1
Unit practice exercises
Suggested answers to self-tests
Suggested answers to unit practice exercises
Appendix
References
Glossary
37
37
37
37
38
45
47
49
55
57
61
95
97
1UNIT 1
Introduction to web development and PHP
Course Overview
Welcome to TCC 242/05 Web Database Application.
This is a course that emphasises both theory and application. It introduces the
concepts, methods and software that will help you create web database applications.
A web database application is a database-driven web application that enables
websites such as online shopping, Internet banking or social networking sites to
be created. In this course, you will learn how to build web database applications
that incorporate authentication and security, and that adhere to industry standards
with respect to database-driven websites.
This course module has five study units. Each unit takes three to four weeks to
complete. The course is structured so that each unit builds on previous ones.
In Unit 1, you will be introduced to the fundamentals of web application
development, web servers and the syntax of the PHP scripting language. PHP is a
powerful server-side scripting language that allows you to build dynamic websites.
You will also be shown how to install Apache web server, PHP and MySQL on
your computer. Unit 2 will focus on the basics of PHP. Here, you will learn PHP
data types, customised functions and control structures. Unit 3 will discuss the
intermediate-level features of PHP such as strings, arrays and files. The discussion
of database integration begins in Unit 4. You will learn how PHP interacts with
MySQL and MySQL library functions. The final unit of this course will cover
the principles of using sessions and cookies for saving state information on a
web page.
The material in this module is presented in a simple, step-by-step format, and it
includes many examples and web programming exercises. Each unit has specific
objectives, activities and self-tests. The activities and self-tests allow you to check
your progress and improve your understanding of what you have learnt. The practice
exercises at the end of each unit allow you to practise the skills that you have
learned so that you can develop proficiency in real-world problem solving.
By the end of this course, you should be able to:
1. Install and configure Apache web server, PHP and MySQL.
2. Create a web database application incorporating functions and control
structures using PHP.
3. Manipulate strings using PHP.
4. Handle web form submissions.
2WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
5. Work with database records and manage user accounts.
6. Use PHP to manipulate database records.
7. Use hidden forms, query strings, cookies and sessions to save state
information.
3UNIT 1
Introduction to web development and PHP
Unit Overview
This unit introduces you to web development methodologies. It introduces the
Apache web server, PHP and MySQL, and discusses the rationale of using
databases on the web. You will also learn how to install and configure the Apache
web server, PHP and MySQL on both Linux and Windows systems. In addition,
you will create web pages that use basic PHP scripts.
Unit Objectives
By the end of this unit, you should be able to:
1. Discuss web development methodologies.
2. Install, configure and run the Apache web server, PHP and MySQL on your
computer.
3. Create web pages using PHP scripts.
4WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
5UNIT 1
Introduction to web development and PHP
1.1 Understanding Web Development
Objectives
By the end of this section, you should be able to:
1. Describe web development methodologies.
2. Describe how information is exchanged between servers and clients.
3. Explain why databases are used on the World Wide Web.
Introduction
A web database application is a database-driven web application. This type of
application is used in Internet banking websites such as Maybank2U.com, online
shopping websites such as Amazon.com and social networking sites like Facebook.
For sites like Amazon.com, even a few minutes of downtime could cost millions
of dollars in lost revenue. Many dotcom failures in the early nineties were caused
by the improper management and underestimation of the scope and features of
web development. In this section, we are going to look at the architecture of a web
application, starting with the methodologies of web development. We will also
show how databases are used on the Web.
Web development A brief description
A website is a place for publishing information using web pages. A web page is
a collection of text, multimedia and hyperlinks that allow users to navigate from
one page to another. Web development is defined as the conception, design and
implementation of a web entity created to serve a specific purpose. The purpose
could be to sell something, promote products or publish information.
Websites can be categorised as personal or professional. Personal sites are mainly
for people to share information about themselves or their products. They may
also just want to get attention, promote their skills or post their curriculum vitae
online to improve their chances of getting a job. Recently, people have started
to publish virtual journals called blogs that describe events in their lives, their
interests or their personal opinions on various topics.
Professional sites are created as portals that showcase businesses and provide
information on their products and services. Some of these portals enable businesses
to sell products online and act as virtual storefronts for receiving orders and payment.
Such sites can directly generate revenue for businesses.
6WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Websites can also be categorised as static or dynamic. Static websites are developed
with fixed-content pages (pages with content that does not change dynamically)
that do not contain any programmatically controlled content. The content will
only change when the website designer manually modifies it.
As the pace of change and business information flows have become more rapid, static
websites are no longer effective at showcasing fast-moving businesses. Dynamic
websites are more effective tools for such businesses. Dynamic websites are driven
by dynamic content that is loaded or created using programming and databases.
The following are some of the popular platforms that are used to create dynamic
websites.
LAMP (Linux, Apache, MySQL and PHP)
This is a popular platform for creating dynamic websites because it is open source,
free of charge and easily adaptable. This course will go into the details of MySQL
and PHP, while also briefly describing Linux and Apache. Linux is an open-source
operating system, Apache is an open-source web server, MySQL is an open-source
database and PHP is an open-source scripting language.
Microsoft .NET
The .NET framework is a platform that was created by Microsoft. It has a huge
library that supports several programming languages like Visual Basic and C#.
It also provides many ready-made tools, templates and applications that assist
developers in creating software. However, to use these tools and templates, developers
have to purchase the appropriate licenses from Microsoft.
Java Struts and JSP
Java Struts and Java Server Pages (JSP) are technologies for developing dynamic
websites with the Java programming language. Java provides a standardised
Integrated Development Environment (IDE), but it is not as intuitive as the
Microsoft Visual Studio IDE.
What platform should I use?
Since LAMP is free and open-source, you should consider using it for web
development projects in which cost is the main constraint. If the software you are
dealing with is written in Java, JSP or Struts could be better candidates. If you are
looking for ease of starting, ready-made tools and templates, technical support
and more robust applications, you should consider .NET.
7UNIT 1
Introduction to web development and PHP
When choosing a platform, you should also consider the following important
aspects of web development:
1. Security
2. Scalability
3. Search engine optimisation
4. Portability
5. Maintenance
6. Administration
Web Reference
You can read more about the Open-Source Software movement at:
1. http://www.opensource.org/
2. http://foss.org.my/
Activity 1.1
1. Web development is defined as
A. a concept that describes the growth of an online business.
B. the conception, design and implementation of a web entity
to serve a purpose.
C. a reference guide for writing a web programming language.
D. the philosophy of how to create and run an online business.
2. Which of the following is not a platform for creating dynamic
websites?
A. JSP
B. LAMP
C. MS.NET
D. Internet Explorer
8WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
3. Personal sites are mainly for people to share information
about themselves or their products. People nowadays publish
virtual journals called _____________ that describe events in
their lives, their interests or their opinions.
4. ____________ websites have pages with fixed content, which
is not programmatically controlled.
5. LAMP is one of the most popular platforms for creating
websites because it is open source, free of charge and easily
adaptable. True / False?
6. What are the important aspects of web development that
you should consider when choosing a platform?
Methodologies for web development
Some web development projects involve minor modifications to existing websites,
while others may involve major development work. To make sure that projects are
delivered on time and within budget, we need to look into several development
methodologies.
Waterfall model (also known as the traditional model)
In this model, systems development is divided into five well-defined sequential
stages. The stages are (Figure 1.1):
1. Analysis: Identifying the problem and formulating how to translate it
into the software domain as a specification.
2. Design: Designing the system.
3. Implementation: Implementing the system for end users in a real-world
scenario.
4. Testing: Testing the system for functionality and bugs, against the initial
specification.
5. Delivery/Support: Handing over the finished product to the customer
and providing software, hardware and usability support.
These stages must be performed sequentially. Hence, the final product will be
delivered when all the stages have been completed.
9UNIT 1
Introduction to web development and PHP
Analysis
Design
Implementation
Testing
Delivery/Support
Figure 1.1 The waterfall model of systems development
The advantages of using the waterfall model in systems development are:
1. It enables you to plan and organise the tasks needed to achieve the main
objective.
Your objective in systems development is to develop a usable system and
deliver it to the user on time. You need to organise your team members’
schedules in order to meet the deadline. The waterfall model enables you
to see where you are heading and it clearly differentiates between the
various stages of the development process. Thus, by using this model as
your fundamental framework, you can plan and organise the workload
for your project.
2. Short development times.
Using the waterfall model will enable short development times as there is
no iterative process involved. Therefore, it enables you to reach your goal
in a shorter time. However, the quality of your system will be affected if
you do not properly complete the tasks in one stage before moving on to
the next.
3. Low cost.
Due to the direct approach to the objective taken by this model, we can
shorten development time. Hence, manpower, documentation and utility
costs can be reduced.
10 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
The disadvantages of the waterfall model are:
1. Not flexible to changes.
The model has a rigid sequence. Hence, you cannot start a new stage until
you have completed the previous stage. In addition, it does not let you
backtrack when you discover problems. As such, errors will accumulate
from stage to stage.
2. System limitations are not discovered until later stages in the development
cycle.
This model does not allow you to backtrack; hence when you discover an
error in a stage, the error will be carried forward to the subsequent stages.
For example, if you make an error in the analysis stage, the error will be
carried to the delivery stage. Therefore, the error will exist in the final
product.
3. Unable to see the whole product until it is finished.
We usually need to see a product before purchasing it. The waterfall model
does not give us the luxury to see the product until the final stage. Thus, if
the user does not like the product, it is too late for changes. If you restart
the project, the cost of development will increase substantially.
For these reasons, the waterfall model is impractical in the real world. When we
develop a system, it is often difficult to anticipate problems that may arise. In
addition, users’ demands change from time to time but the waterfall model is not
flexible enough to cope with the changes. Consequently, we need a model that is
flexible and able to cope with changes. This leads us to the next model, namely
the iterative development model.
Iterative development model
This model is similar to the waterfall model in that we still have to go through the
analysis, design, implementation, testing and delivery stages. However, an iterative
process has been added to the model, so that each stage can provide feedback to
the stages that precede it. This iterative process enables you to refine the system
or amend errors before progressing to the next stage.
As you can see in Figure 1.2, the iterative process has been added to the waterfall
model to create the iterative development model. This model enables feedback to
be iterated between stages until you are satisfied with the result. For example, you
can iterate between the analysis and design stages until the result is acceptable. If
problems are discovered at the implementation stage, you can go back to either
the design stage or the analysis stage.
11UNIT 1
Introduction to web development and PHP
Analysis
Design
Implementation
Testing
Delivery/Support
Figure 1.2 The iterative development model
The advantages of using the iterative development model in systems development
are:
1. Problems can be discovered and rectified at an early stage.
You still carry out the various stages, but not in a manner as rigid as in
the waterfall model. Errors discovered at an early stage can be rectified. As
such, the accumulation of errors from stage to stage can be eliminated.
2. Can cope with changes.
At any point of the process, you can decide to continue, amend or stop
the project. This flexibility is important because unexpected circumstances
or changes in user’s requirements can arise. By providing flexibility during
the development of a system, changes can be made by the developer,
stakeholders and users without unduly increasing costs.
3. A better quality system.
Due to the flexibility of iteration, you can refine each stage until you are
ready to move on. In addition, when you iterate between stages, you may
discover new ideas or better ways to implement the system.
12 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
The disadvantages of using the iterative development model are:
1. Limited application range.
The iterative development model is only applicable for developing business
applications and not really suitable for technical applications. Hence, its
focus is narrower.
2. The process can be messy.
Due to its flexibility, there might be so many changes that it is difficult to
keep track of all of them. In addition, you can be so drawn to new ideas
as you keep iterating between the stages that the main objective of the
system becomes lost in the process.
3. Costs can increase.
Excessive iteration can increase development time. When development
time is increased, development costs will increase as well.
Prototype approaches
The essence of iterative design is to build, test and then refine the design. We need
an approach that enables us to quickly build a system and obtain useful feedback.
Prototyping is such an approach. There are three types of prototyping:
1. Throwaway (rapid) prototyping technique
Throwaway prototyping is also known as rapid prototyping. A prototype
built using this technique will not be used as part of the final system.
This technique requires that the prototype be built quickly so that
information can be promptly collected and used in the development
life cycle.
Preliminary
requirements
Build
prototype
Evaluate
prototype
no yes
Adequate? Final
requirements
Figure 1.3 The throwaway (rapid) prototyping technique
13UNIT 1
Introduction to web development and PHP
As you can see from Figure 1.3, a prototype will be built after the preliminary
requirements analysis. Then you will evaluate the prototype. If the prototype
is adequate, you may move to the final requirements specification. Here,
adequacy means that the design knowledge gained from the prototype is
good enough to derive the final requirements. If the prototype is found to
be inadequate during testing, you need to rebuild and then re-evaluate the
specifications/ideas until they are acceptable to the user. In the throwaway
technique, the prototype will be discarded upon completion of the final
requirements specification. This method enables you to see the overall
features of the system before it is completed.
2. Incremental technique
The idea here is to save time between the specification and delivery stages.
This requires a compromise between the developer and the clients. A large
system will be broken down into components and installed separately. The
developer will first set up the skeleton of the system at the client’s premises.
Then, the installation of different components is carried out progressively.
This incremental approach uses one overall design, even though different
components are added at different times. At the end of this progressive
process, the entire system will be in place. The advantage of this approach
is that it enables a prototype to be tested at the location where the finished
system will be used. Changes to the critical features of the system are
possible as it is being built by adding components incrementally.
Identify
components Req
Arch
Det
Impl
Int
deliver
increment
deliver
system
no yes
System
complete? Operation and
maintenance
Designing
component/prototype
Figure 1.4 Incremental technique
Note: Req = requirements specification, Arch = architectural design, Det =
detailed design, Imp = implementation and testing, Int = integration and
testing.
14 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
3. Evolutionary technique
In the evolutionary prototyping approach, a prototype is first developed. It
will then be evaluated and continually evolved into a fully functional system.
The advantage of this method is that it can cope with changes during and
after development.
Req
Arch
Det
Impl
Int
Build
prototype
Evaluate
prototype
Operation and
maintenance
Figure 1.5 The evolutionary technique
Extreme programming
Extreme programming (XP) is one of the popular Agile systems development
methods. It is a model that works in a rapidly changing environment. The XP model
encourages developers to work in pairs to promote synergy and to support each
other. Developers are also required to write their own test scripts for the software
that they have created. This model assumes that developers are good at teamwork
and are highly committed to their work.
An XP team emphasises on customer satisfaction as it is expected to quickly deliver
tangible results. Thus, this approach needs the heavy involvement of the customer’s
representatives in development meetings. The XP model is optimised for small
team projects that require less than 20 people.
Scrum
Scrum is another Agile approach to software development. Scrum uses iterative
development to address requirement changes. The model refers to these repetitions
as sprints that usually last for 3 to 4 weeks. Each sprint needs to achieve some targets.
For example, Sprint #1 may be required to deliver a part of the project such as
the web authentication logic and mechanism.
In this approach, the entire team will spend 10 to 15 minutes in “standup” meetings
every morning before they start work. Team members will update each other on
tasks that were performed after the last standup meeting, tasks to be accomplished
15UNIT 1
Introduction to web development and PHP
on that day and problems that they faced. They will not resolve the problems
during the standup meeting. The problems will be solved outside of the meeting
so that team members who are not involved with the problem can go about their
own tasks.
At the end of a sprint, the customer’s representative will be invited to a demonstration
of the features that were implemented in that particular sprint. For example, the
developers may demonstrate the login box, user registration page and password
retrieval mechanism that were developed based on the targets set for that sprint.
Scrum also works for large projects (Schwalbe 2004).
Web Reference
The following web references present a comprehensive view of
various web development methodologies:
1. “Successful Web Development Methodologies”
http://articles.sitepoint.com/article/successful-development
2. “Extreme Programming: A gentle introduction”
http://www.extremeprogramming.org/
3. “Scrum Methodology”
http://scrummethodology.com/
Activity 1.2
State whether each of the following is True or False.
1. In the methodology of web development, many developers
agree with the waterfall model, which states that, in practice,
it is feasible to finish a stage perfectly before moving to the next
stage because customers will never change their requirements.
2. Extreme Programming is a model that works in a rapidly
changing environment, encourages developers to work in pairs
and requires developers to write their own test scripts for the
software they have developed.
16 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Databases on the Web
When we surf the Internet, we use a web browser such as Internet Explorer or
Firefox to request information from a web server. The request could be submitted
as a form, by clicking on hyperlinks or by entering URLs in our web browser.
The web server will then respond to our web browser. At the basic level, the Web
has a client/server architecture in which the web server is the server and the web
browser is the client. Figure 1.6 shows the client-server architecture of the Web.
Web Browser Web
Server
Request
Response
Figure 1.6 Client-server architecture of the Web
The web server is not a dedicated storage area. Complex data manipulation
operations, especially on commercial sites, should be handled by a separate database
server. Figure 1.7 shows how a web browser requests a resource from a database
server and how the database and web servers respond to the request. The browser
is still the client, but the web server is now the middle tier and the database
server is the database tier of the architecture.
Web Browser Web
Server
Database
Server
Figure 1.7 A web browser requesting a resource from a database server
Most of the websites that we visit today are powered by web database applications.
Web-based email, e-commerce sites and online shopping sites are all database-driven.
To build a practical and powerful website, you need to develop a web database
application.
In order to build web database applications, we need to have a web server such as
Apache and a database server such as MySQL. Apache is one of the popular web
servers and works best in Unix/Linux-based systems. It can also be implemented in
Windows-based systems. As it is open-source, developers can write code to extend
the functionality of Apache. It is an extremely quick and stable web server.
MySQL is particularly suitable for web applications. You can install and use
MYSQL at no cost. MySQL is fast and powerful when used for building small- to
medium-sized databases. As it is open source, updates and feature improvements
are frequently added.
17UNIT 1
Introduction to web development and PHP
The key consideration here is to come up with an efficient and reliable way for the
web server to communicate with the database. Using PHP is one of the better ways
of accomplishing this task. PHP is a powerful, open-source, server-side scripting
language particularly suited to web database applications because of integration
tools available in the web server and database environments. PHP provides the
capability to interact with almost all popular database servers.
Web Reference
The following web references present a comprehensive view of
websites and web applications:
1. “Web Site vs Web Application”
http://www.tonymarston.net/php-mysql/web-site-vs-web-
application.html
2. “PHP”
http://www.php.net/
3. Apache”
http://www.apache.org/
Activity 1.3
1. What happens to the web server when we click on a hyperlink
in a web page?
2. Why is MySQL suitable for web applications?
3. Apache is a popular web server that works in Unix systems
but cannot run under Windows. True / False?
18 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Summary
In this section, you have learnt the basics of web development. The
various web development methodologies were briefly described
and their advantages and disadvantages were discussed. You were
also introduced to the application of databases on the Web. In the
next section, you will be given step-by-step instructions on how
to install Apache, MySQL and PHP on your computer. You will
use these open-source software to build web database applications.
Self-test 1.1
1. A website is a place for publishing information using web
pages. A web page may contain text, images and hyperlinks
for users to navigate from one page to another. True / False?
2. Professional sites are created to describe a business, provide
contact information and to generate revenues for a business.
True / False?
3. As business information flows and the pace of change have
become more rapid, dynamic websites have become effective
tools for achieving business success. Dynamic websites
have dynamic content that is loaded by ______________ or
_______________.
4. Linux is an open-source _______________, Apache is an
open-source ______________, MySQL is an open-source
_____________, and PHP is an open-source _____________.
A. web server; operating system; database; programming
language
B. programming language; operating system; database; web
server
C. programming language; web server; database; operating
system
D. operating system; web server; database; web programming
language
5. Describe how incremental prototyping is useful in web
development.
19UNIT 1
Introduction to web development and PHP
6. What are the two popular Agile models of web development?
7. An XP team spends 10 to 15 minutes in a “standup” meeting
every morning before its members start work. True / False?
8. What is Scrum?
9. Compl ex data manip ulation operations, especially on
commercial site s , s h o u l d be handled by a separate
_______________.
A. data server
B. programming language
C. web server
D. web browser
10. PHP is an open-source programming language that is particularly
suited to web database applications because of integration
tools available in the web server and database environments.
True / False?
20 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Suggested answers to activities
Feedback
Activity 1.1
1. B
2. D
3. blogs
4. Static
5. True
6. Security
Scalability
Search engine optimisation
Portability
Maintenance
Administration
Activity 1.2
1. False
2. True
Activity 1.3
1. When we click on a hyperlink, the web browser requests
information or a resource from a web server. The web server
will then respond to the web browser and deliver the information
or resources that were requested.
21UNIT 1
Introduction to web development and PHP
2. MySQL is open source and free, so you can install and use it
without paying anything. It is fast and powerful when used for
building small- to medium-sized databases. Updates and
feature improvements are frequently added to MySQL.
3. False
22 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
23UNIT 1
Introduction to web development and PHP
1.2 Installing and Configuring Apache,
MySQL and PHP
Objectives
By the end of this section, you should be able to:
1. Install and configure the LAMP system under Ubuntu on your computer.
2. Configure the Apache web server to work with PHP.
3. Interact with MySQL using basic SQL queries.
Introduction
This section introduces you to the general techniques for installing the Apache
web server, MySQL and PHP on a Linux (Ubuntu) system. Apache is one of the
most popular web servers and works best on Unix or Linux systems. However, it
works well on the Windows system too. Understanding the techniques to install
and configure a web server is essential to hosting your own web application. The
following installation guide is for the Linux system. For the Windows system,
please refer to the Appendix.
Note: The following guide uses Linux Ubuntu 10.10. You can download Ubuntu
from www.ubuntu.com. It is assumed that you have basic knowledge of installing
and operating Ubuntu. For more information on Ubuntu installation, please
refer to the following web pages:
1. “Ubuntu Documentation  Installation”: https://help.ubuntu.com/
community/Installation
2. “Installing Ubuntu 10.10”: http://news.softpedia.com/news/Installing-
Ubuntu-10-10-160966.shtml
Installing LAMP
Linux (Ubuntu) will be the platform for the Apache, PHP and MySQL components
that you will be installing and using soon. You will be installing LAMP (Linux,
Apache, MySQL and PHP) packages from within Ubuntu. Once you have an
understanding of how to set up LAMP on Ubuntu, you will be able set it up on
other Linux versions as well.
24 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Installation steps
1. Open the terminal window (also known as the command line or console
window). On the Ubuntu desktop, go to Applications > Accessories >
Terminal. You will then see a command-line window like the one shown
in Figure 1.8.
Figure 1.8 Opening a terminal window in Ubuntu
2. Enter the following command in the command-line window:
sudo apt-get install lamp-server^
This is the general command used to install a program and package in the
Ubuntu system. The command sudo means that you will be running the
command with root (administrator) privileges. You will be prompted to
enter a password. Notice the caret (^) symbol at the end of the command.
It is not a typo and must be included.
25UNIT 1
Introduction to web development and PHP
3. Hit the <Enter> key after the command and you will be shown the packages
that need to be installed. Type Y and hit <Enter> to begin the installation.
Figure 1.9 Packages that need to be installed for LAMP
4. The installation begins and you will be prompted to enter a new password
for the MySQL root user (Figure 1.10). Type wawasan as the password
for our purposes. Hit <Enter> to continue. If there is no response or the
on-screen <Ok> button is not highlighted in red, hit the <Tab> key to
move the focus to the <Ok> button.
Figure 1.10 Entering a new password for the MySQL root user
26 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
5. You will be asked to confirm the password. Re-type the same password
and the installation will then continue until it is complete.
6. That’s it, the LAMP installation is done! Congratulations! Now you just
need to run some configuration processes and tests to confirm your
installation.
Activity 1.4
1. What is LAMP and why do we want to install it?
2. __________________ is the single line command that will
install the LAMP (Linux, Apache, MySQL and PHP) packages
from Ubuntu.
Testing the configurations of Apache, PHP and MySQL
You can use the following steps to test the configurations of Apache, PHP and
MySQL. You will first test the Apache server.
Apache
1. At this stage, the Apache web server should have been installed on your
computer. Type the following in the terminal to check the version of
Apache that was installed: apache2 -v
Figure 1.11 Checking the version of Apache that was installed
27UNIT 1
Introduction to web development and PHP
2. The version will be displayed. Check if the Apache service is running by
typing service apache2 status.
Figure 1.12 Confirming that the Apache service is running
3. If the service is not running, type the following command to start the
service:
sudo service apache2 start
4. Once you have confirmed that the Apache service is running, you can
test the Apache server by entering http://localhost on the web browser. If
the installation is successful, you will be able to see the default Apache page
that has the “It works!” headline (Figure 1.13). If you cannot see this page,
visit the ‘error.log’ file located in the ‘/var/log/apache2/’ folder to see what
went wrong with your installation.
Figure 1.13 Testing your Apache installation
28 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
PHP
1. After confirming that Apache is running, we can then test the PHP
installation. By default, the document root directory for Apache is the
‘/var/www/’ directory. Note that you can change the document root
directory path in the ‘/etc/apache2/sites-available/default’ file under the
“DocumentRoot” section.
2. Let’s retain the default document root directory as ‘/var/www/’ and create a
‘test.php’ file in it. Open the terminal and call up the nano editor by
entering:
sudo nano /var/www/test.php
3. Enter the following PHP code into the new text file:
<?php phpinfo(); ?>
Figure 1.14 Entering PHP code using the nano editor
4. Hit <Ctrl> + <x> to exit the editor. Save the code you entered earlier
by typing Y and hitting <Enter> for the default format option.
5. To ensure that the changes are updated in Apache, restart the Apache
server using the following code on the terminal line:
sudo service apache2 restart
29UNIT 1
Introduction to web development and PHP
6. You can now test the page you created by entering http://localhost/
test.php on a web browser.
You should get the PHP information page shown in Figure 1.15.
Figure 1.15 Viewing PHP information on the Apache server
Web Reference
To learn more about configuring Apache with PHP, please read
the following:
“Ubuntu 10.10 PHP5 Scripting Language” at: https://help.
ubuntu.com/10.10/serverguide/C/php5.html#php5-configuration
30 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
MySQL
1. After the installation, you should make sure that the MySQL database is
bound to your localhost IP address. At the terminal, type:
cat /etc/hosts | grep localhost
2. You can also verify the localhost bind address at ‘my.cnf’ of MySQL.
cat /etc/mysql/my.cnf | grep bind-address
Figure 1.16 Verifying that MySQL is bound to your localhost IP address
3. Notice that the bind-address = 127.0.0.1 (Figure 1.16)
4. Check that the MYSQL service is running by typing:
service mysql status
Figure 1.17 Checking that the MySQL service is running
31UNIT 1
Introduction to web development and PHP
5. If the service is not running, type the following command to start the
service:
sudo service mysql start
6. After confirming that the MYSQL service is running, check the databases
in the MySQL version that was installed. Follow the steps below to do this.
7. Type the following to enter the MySQL monitor:
mysql –h localhost –u root –p
8. You will be prompted to enter a password. Enter the password wawasan
that you set earlier.
Figure 1.18 Entering the MySQL monitor
9. You will then be in the MySQL monitor with the “mysql>” prompt showing
on-screen. All commands used here will end with a semicolon “;” or “\g.
View your pre-installed databases by typing:
show databases;
Do not forget to add the semicolon before you execute your command.
You will then see some pre-installed databases listed. However, you might
not have databases that are identical to those shown in the following figure.
Figure 1.19 The MySQL monitor showing a list of databases
32 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
10. You can list all the tables in the database by typing:
a. use mysql to use the ‘mysql’ database.
b. show tables; to list all the tables in the database.
Figure 1.20 The MySQL monitor showing a list of tables
11. Next, you can list the users in your MySQL system. In this case, you
should already have a localhost root user with the password that you
entered. Type:
SELECT User, Host, Password FROM mysql.user;
Note that the password is hashed for security purposes.
Figure 1.21 The MySQL monitor showing a user list
If everything works, you should get the results shown in Figure 1.21.
If so, congratulations, your MySQL installation is fine.
33UNIT 1
Introduction to web development and PHP
Type exit twice to exit the MySQL monitor and terminal. Notice that
you have just used the SQL query language to obtain the user list. The
SQL query that you used was:
SELECT User, Host, Password FROM mysql.user;
The query is an example of the SQL SELECT statement, which is used to
select data from a database. The general syntax of this statement is:
SELECT column_name(s) FROM table_name;
Do not worry about SQL commands for now. We are just giving you
some basic knowledge on how you can interact with MySQL using the
SQL query language. You will go into the details of SQL when you learn
about MySQL in Unit 4.
Web Reference
To learn more about MySQL post-installation procedures, please
visit “Unix Postinstallation Procedures” at:
http://dev.mysql.com/doc/refman/5.1/en/unix-postinstallation.
html
Activity 1.5
1. Once you have confirmed that the Apache service is running,
you can te st the Apache server by entering http://
_______________________ on your web browser.
2. In a PHP content page, you enter the code _____________
______________ to test that PHP is working and to display
information about PHP, Apache and MySQL on your system.
34 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Summary
This section discussed the common techniques for installing
Apache, MySQL and PHP in the Linux system. We have chosen
to install the LAMP packages via a package manager because it is
easier to do so. We are sure that you will be able to do the same
by following the step-by-step guide provided in this section.
We have also prepared a version of the installation guide for the
Windows operating system. For Windows, we will be installing the
components individually so that you will be exposed to different
ways of doing things. If you need to install the packages in
Windows, please refer to the Appendix.
In the next section, we will discuss basic PHP syntax and
language constructs. You will also learn how PHP is embedded in
a web page.
Self-test 1.2
1. In the Linux system, what is the command to check the
Apache 2 service status?
2. You can change the document root directory path of the ‘/etc/
apache2/sites-available/default’ file under the ___________
section.
A. ApacheRoot
B. DefaultDirectory
C. DocumentRoot
D. RootDirectory
3. What is the command to enter the localhost MySQL monitor
with root privileges?
4. All commands used in the MySQL monitor will end with either
a ____________ or ____________.
A. semicolon, \g
B. comma, \g
C. semicolon, \end
D. comma, \end
35UNIT 1
Introduction to web development and PHP
Suggested answers to activities
Feedback
Activity 1.4
1. LAMP is a software bundle consisting of Linux, Apache,
MySQL and PHP. We install LAMP to build an Apache
web server in the Linux operating system. Apache will
host a web database application via PHP, the middle-tier
programming language and MySQL, the database component.
2. sudo apt-get install lamp-server^
Activity 1.5
1. localhost or 127.0.0.1
2. <?php phpinfo(); ?>
36 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
37UNIT 1
Introduction to web development and PHP
1.3 Creating Basic PHP Scripts
Objectives
By the end of this section, you should be able to:
1. Describe and use basic PHP syntax and language constructs.
2. Embed PHP code in a web page.
Introduction
PHP, as a server-side scripting language, is intended largely for the Web environment.
PHP has gained quite a following in recent times, and it is one of the forerunners
of the Open-Source Software movement. Its popularity is due to its syntax, which
is similar to that of the C programming language, and its simplicity. Basically,
PHP allows a static web page to become a dynamic one. “PHP” is an acronym
that stands for “Pre-Hypertext Processor”. This means that PHP code is parsed on
a server before it creates HTML. PHP file names end with the “.php” extension.
This extension notifies a web server that PHP code needs to be parsed before
HTML is displayed on a web browser.
Overview of PHP syntax
PHP syntax is relatively straightforward. In this section, you will learn the general
rules and basic syntax of PHP. The following are three basic rules that apply
to PHP:
1. PHP statements are enclosed within the opening tag <?php and closing tag
?>:
<?php PHP code ?>
or
<?php
PHP code
?>
It does not matter if both the tags are on one line or if the second one starts
on a new line. To a server, the code will show up as one continuous line,
regardless of tabs or new lines. It is up to us to arrange the code so that
it is organised and easily understood by people who may want to modify
the code.
38 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
2. PHP statements end with a semicolon:
<?php
PHP statement one;
PHP statement two;
?>
3. PHP comments are represented by double slashes // for a single-line
comment or by /* and */ for several lines of comment:
// This is a single-line comment
/*
This is a multiple-
line comment
*/
Comments are used throughout the code to explain the purpose of the
code to people. We encourage you to use as many comments as you
think are necessary, so that other developers can easily understand your
programming.
Note: The following discussion assumes that you have basic knowledge of HTML.
Web Reference
For a tutorial on HTML, please refer to the following website:
“HTML Tutorial”, http://www.w3schools.com/html/default.asp
Creating your first web page with PHP
As you may already know, web pages are actually generated by HTML code. A
HTML document begins with a <html> tag and ends with a </html> tag. A typical
HTML page is shown below:
<html>
<head>
<title> HTML document </title>
</head>
<body>
Content of the page.
</body>
</html>
39UNIT 1
Introduction to web development and PHP
If we save the content above into a file with the extension “.html” (e.g., ‘first.html’),
we can display this page in a web browser like Internet Explorer or Firefox.
Figure 1.22 A web page generated by HTML code
We will be able to see the HTML source code that generated this web page by going
to View > Source in Internet Explorer.
Figure 1.23 The HTML source code of a web page
Notice that every opening tag, such as <head>, will always end with an ending tag
that comes with a forward slash, such as </head>. PHP works in almost the same
way. Every PHP opening tag will also end with an ending tag. The difference is
that PHP code is hidden from web page visitors as PHP is a server-side scripting
language. The only code that the visitors can see is the resulting HTML output.
40 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Let’s start creating our first PHP script by using the echo function to print text
in a web browser. We will reproduce the HTML code that we wrote earlier by
using the PHP echo function. The echo function is used inside the PHP tags.
We also change the content in the title tag to “PHP document” as shown below.
<html>
<head>
<title> PHP document </title>
</head>
<body>
<?php
echo “Content of the page.”;
?>
</body>
</html>
We then save the content above into a file with the “.php” extension (e.g., ‘first.
php’). A web page with the “.html” extension can be displayed from anywhere
on the local disk. But as PHP is a server-side page, the file needs to be placed on
the Apache server that we installed earlier. The location to store the server pages
is ‘/var/www/ for Linux or ‘C:\Program Files\Apache Software Foundation\
Apache2.2\htdocs’ for Windows. Save the ‘first.php’ file there and display this
page in a web browser by entering localhost/first.php.
Figure 1.24 Web page displayed by embedded PHP code
41UNIT 1
Introduction to web development and PHP
Notice that you get the same result as that of the earlier HTML page except that
the title of the page is now “PHP document”. Access the source code by going to
View > Source on Internet Explorer. You will see HTML code that is nearly
identical to the code that generated the HTML-only web page.
Figure 1.25 HTML source code produced by PHP code
You should notice from looking at the source code that the PHP tags and echo
function are all hidden from web page visitors. They only get to see the resulting
HTML output. This will provide more security and flexibility to your PHP code.
PHP can also be written as a pure PHP program without being enclosed in HTML
tags. Pure PHP code can be used to store business logic such as calculations and a
separate HTML file is then used as the presentation layer. The advantage of doing
this is that the same business logic can be reused for different presentations. You
will learn more about the use of pure PHP code in the following units. An example
is shown below.
<?php
echo “<html>”;
echo “ <head>”;
echo “ <title> Pure PHP document </title>”;
echo “ </head>”;
echo “ <body>”;
echo “ Content of the page.”;
echo “ </body>”;
echo “</html>”;
?>
42 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Figure 1.26 A web page created by pure PHP code
Congratulations, you have just created your very first PHP page.
Activity 1.6
1. “PHP” in the context of the scripting language for web
development is an acronym that stands for “Personal Hypertext
Protocol”. True / False?
2. A single line of PHP code ends with ____________.
A. double slashes (//)
B. an asterisk followed by a slash (*/)
C. the hash key (#)
D. a semicolon (;)
3. A HTML document begins with a ___________ tag and ends
with a __________ tag.
A. <body>, </body>
B. <head>, </head>
C. <html>, </html>
D. <title>, </title>
43UNIT 1
Introduction to web development and PHP
Web Reference
To learn more about basic PHP syntax, please visit:
“PHP Basic Syntax”, http://www.php.net/manual/en/language.
basic-syntax.php
Summary
You should now have some idea of what PHP code looks like
and how PHP can be integrated into HTML code to create
dynamic web pages. To summarise, you should now be familiar
with:
1. PHP basic syntax.
2. The purpose of using comments throughout program code.
3. How PHP, as a server-side scripting language, gives you
flexibility.
4. How to create a HTML web page using a pure PHP program.
In the next unit, you will learn about variables and data types, and
learn how to create functions and control structures. You will also
write a PHP program that contains a function that you will write
yourself.
Self-test 1.3
1. PHP file names end with a .php extension to notify the server
that PHP code needs to be parsed before the HTML web
page is displayed in the user’s web browser. True / False?
2. The more comments you put into your PHP program code,
the more processing time is needed by the web server to
display a web page in a browser. True / False?
44 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
3. PHP code is always enclosed within the opening tag _______
and the closing tag ________.
A. <!-- … -->
B. <% … %>
C. <? … ?>
D. <?php … ?>
4. PHP comments are represented by _________ for a single-line
comment and by _________ for several lines of comment.
A. <?php and <? … ?>
B. and ” … “
C. // and <!-- … -->
D. // and /* … */
5. The following PHP function is used to print text in a web
browser:
A. write
B. echo
C. println
D. printing
6. Which of the following tags will not be visible in the web page
source code when you go to View > Source on Internet
Explorer?
A. <?php
B. <body>
C. </html>
D. <head>
7. What is the output produced in a web browser by the following
PHP code?
<?php echo “This is TCC242\\05”; ?>
A. This is TCC242\\05
B. This is TCC24205
C. This is TCC242\05
D. “This is TCC242\\05”
45UNIT 1
Introduction to web development and PHP
8. What is the output produced by the following PHP code?
<?php echo “echo”; echo”;”; ?>
A. echo;
B. echo
C. echo”; echo”;
D. ;
9. What is the PHP code that produces the following result in a
web browser?
<?php
A. <?php echo”<?php “; ?>
B. <?php echo”&lt;?php “; ?>
C. <?php echo”\<?php “; ?>
D. <?php echo”<\?php “; ?>
10. What is the PHP code that produces the following result in a
web browser?
18/01/2011 11:41:02
A. <?php echo date(“H:i:s d/m/Y”) ?>
B. <?php echo date(“H:i:s m/d/Y”) ?>
C. <?php echo date(“m/d/Y H:i:s”) ?>
D. <?php echo date(“d/m/Y H:i:s”) ?>
Suggested answers to activity
Feedback
Activity 1.6
1. False
2. D
3. C
46 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
47UNIT 1
Introduction to web development and PHP
Summary of Unit 1
Summary
In this unit, you learnt about the development of different
types of web sites. You also learnt about popular programming
platforms that are used to create dynamic websites. You looked at
several development methodologies, including the two popular
development models in the Agile group of methodologies,
which are used to ensure that web projects are delivered on
time and within their scope and budget. You have also seen how
databases are used on the Web.
In the second section, you learnt how to install, configure, run
and test the Apache web server, MySQL and PHP on Linux
systems. The installation procedures for Windows systems are
covered in the Appendix. In the final section, you studied basic
PHP syntax and discovered how PHP, as a server-side scripting
language, gives you flexibility. You also learnt to write and execute
a pure PHP program.
In the next unit, you will focus on PHP variables and data types,
and learn about the constructs that PHP provides for controlling
program execution flow.
48 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
49UNIT 1
Introduction to web development and PHP
Unit Practice Exercises
1. Create a PHP file in the ‘/var/www/Unit1’ directory (or ‘<Apache Directory>\
htdocs\Unit1’ in Windows) and name it ‘MySite01.php’.
The PHP web page will consist of a title, a welcome message, your name
and a message stating the current day, as laid out in the following table.
Object Markup Value/Example
Title <Head><Title>…</Title></Head> My Site 01
Welcome
Message
<body>
<h1>…</ h1>
</body>
Welcome, {Your
name}!
Current Day <?php
// set the default time zone
date_default_timezone_set(‘Asia/
Kuala_Lumpur’);
// use echo function to write
the string
// Today’s date
echo date(“d F, Y”);
?>
Today is
09 January, 2011
Create the page as shown in the following figure.
50 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
2. In this exercise, you will modify the web page from question 1. Duplicate the
PHP file from question 1 in the ‘/var/www/Unit1’ directory (or ‘<Apache
Directory>\htdocs\Unit1’ in Windows) and rename it ‘MySite02.php’.
a. Copy and paste the contents of the “About Wawasan” message into the file.
b. Insert the footer note that includes your e-mail address.
Object Markup Value/Example
Title <Head><Title>…</Title></Head> My Site 02
About
Wawasan page
<p>
</p>
{Copy About
Wawasan page
from http://wou.
edu.my/about_
overview.aspx}
Footer note <br>
<span style=”font-size:x-
small”>The site is developed
by <a hre f = m ailto : { y o ur_
email}”>{Your_Name}</a>
e.g., “The site is
developed by John
Doe”
The results should look like the figure below.
51UNIT 1
Introduction to web development and PHP
3. In this exercise, you will modify the web page from question 2. Duplicate the
PHP file from question 2 in the ‘/var/www/Unit1’ directory (or ‘<Apache
Directory>\htdocs\Unit1’ in Windows) and rename it ‘MySite03.php’.
a. Add the current time after the date by using the PHP function shown below.
b. Insert Javascript code to update the clock every second.
Object Markup Value/Example
Title <Head><Title>…</Title></
Head>
My Site 03
PHP current
time
// echo a space before the
current time
<?php echo date(“G:i:s”);
?>
e.g., 2:39:14
Insert
Javascript into
the <head>
<script>
</script>
function showTime () {
var time = new Date()
var hour = time.
getHours()
var minute = time.
getMinutes()
var sMin =
(minute<10) ? “0” +
minute : minute
var second = time.
getSeconds()
var sSecs =
(second<10) ? “0” +
second : second
var strTime = hour + “:”
+ sMin + “:” +sSecs
document.
getElementById
(“clockFace”).
innerHTML = strTime;
}
clockFace id
placement
<span id=”clockFace”
><?php echo date(“G:i:s”);
?></span>
e.g., 2:39:14
Set interval to
showTime in
body tag
<BODY onload=”setInterval
(showTime, 1000)”>
e.g., Time will
auto update
2:39:15…16…17
The resulting web page should look like the one shown in the figure below.
52 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Compare your results with the figure below.
4. In this exercise, you will modify the web page from question 3. Duplicate
the PHP file from question 3 in the ‘/var/www/Unit1’ directory (or ‘<Apache
Directory>\htdocs\Unit1’ in Windows) and name it ‘MySite04.php’.
a. Use the PHP random function to load a colour.
b. Use the randomly loaded colour as the background colour of the web page.
Object Markup Value/Example
Title <Head><Title>…</Title></Head> My Site 04
PHP random
function
<?php
echo(dechex(rand(0,255)).
dechex(rand(0,255)).
dechex(rand(0,255)));?>
e.g., 296746
Insert the
PHP random
function into
the body tag
‘bgcolor’
<BODY bgcolor=”#<?php
echo(dechex(rand(0,255)).
dechex(rand(0,255)).
dechex(rand(0,255)));?>” …>
Background colour
will change every
time the page is
refreshed.
The following figure shows the result of the modification. Of course, changes
in background colour can be better observed in a web browser than on a
black-and-white paper page!
53UNIT 1
Introduction to web development and PHP
54 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
55UNIT 1
Introduction to web development and PHP
Suggested Answers to Self-tests
Feedback
Self-test 1.1
1. True
2. True
3. programming languages, databases
4. D
5. Incremental prototyping:
a. Allows large systems to be developed in phases with each
release providing additional capabilities.
b. In this model, the most important features of a system are
developed to completion first and less important features
are added later.
c. Speeds up the implementation of a project.
6. Extreme Programming and Scrum.
7. False
8. Scrum is an Agile model that uses iterative development
periods called sprints that usually last for 3 to 4 weeks. Each
sprint achieves some targets. The team needs to meet up
every morning before they start work to discuss development
issues. At the end of a sprint, features that have been completed
in that particular sprint are demonstrated to the customer’s
representative.
9. A
10. True
56 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Self-test 1.2
1. service apache2 status
2. C
3. mysql h localhost –u root –p (and enter the root
password)
4. A
Self-test 1.3
1. True
2. False
3. D
4. D
5. B
6. A
7. C
8. A
9. B
10. D
57UNIT 1
Introduction to web development and PHP
Suggested Answers to Unit Practice
Exercises
Feedback
1. MySite01.php
<HTML>
<HEAD>
<TITLE>My Site 01</TITLE>
</HEAD>
<BODY>
<h1>Welcome, John!</h1>
<?php
// set the default time zone
d a t e _ d e f a u l t _ t i m e z o n e _ s e t ( A s ia/Kuala_
Lumpur’);
// Today’s date
echo “Today is “;
echo date(“d F, Y”);
echo “ “;
?>
</BODY>
</HTML>
2. MySite02.php
<HTML>
<HEAD>
<TITLE>My Site 02</TITLE>
</HEAD>
<BODY>
<h1>Welcome, John!</h1>
<?php
// set the default time zone
d a t e _ d e f a u l t _ t i m e z o n e _ s e t ( A s ia/Kuala_
Lumpur’);
// Today’s date
echo “Today is “;
echo date(“d F, Y”);
echo “ “;
?>
<p>
// Copy About Wawasan page from http://wou.
edu.my/about_overview.aspx
</p>
<br>
<span style=”font-size:x-small”>The site
is developed by <a href=”mailto:johndoe@
nothing.com”>John
Doe</a></span>
</BODY>
</HTML>
58 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
3. MySite03.php
<HTML>
<HEAD>
<TITLE>My Site 03</TITLE>
<script>
function showTime () {
var time = new Date()
var hour = time.getHours()
var minute = time.getMinutes()
var sMin = (minute<10) ? “0” + minute : minute
var second = time.getSeconds()
var sSecs = (second<10) ? “0” + second : second
var strTime = hour + “:” + sMin + “:” +sSecs
document.getElementById(“clockFace”).innerHTML
= strTime;
}
</script>
</HEAD>
<BODY onload=”setInterval(showTime, 1000)”>
<h1>Welcome, John!</h1>
<?php
// set the default time zone
date_default_timezone_set(‘Asia/Kuala_Lumpur’);
// Today’s date
echo “Today is “;
echo date(“d F, Y”);
// echo a space before the current time
echo “ “;
?>
<span id=”clockFace” ><?php echo date(“G:i:s”);
?></span>
<p>
// Copy About Wawasan page from http://wou.edu.
my/about_overview.aspx
</p>
<br>
<span style=”font-size:x-small”>The site is
developed by <a href=”mailto:johndoe@nothing.
com”>John
Doe</a></span>
</BODY>
</HTML>
59UNIT 1
Introduction to web development and PHP
4. MySite04.php
<HTML>
<HEAD>
<TITLE>My Site 04</TITLE>
<script>
function showTime () {
var time = new Date()
var hour = time.getHours()
var minute = time.getMinutes()
var sMin = (minute<10) ? “0” + minute : minute
var second = time.getSeconds()
var sSecs = (second<10) ? “0” + second : second
var strTime = hour + “:” + sMin + “:” +sSecs
document.getElementById(“clockFace”).innerHTML
= strTime;
}
</script>
</HEAD>
<BODY bgcolor=”#<?php echo(dechex(rand(0,255)).
de c hex( r and ( 0,25 5)). d ech e x(ra n d(0 , 255) ) );? >
onload=”setInterval(showTime, 1000)”>
<h1>Welcome, John!</h1>
<?php
// set the default time zone
date_default_timezone_set(‘Asia/Kuala_Lumpur’);
// Today’s date
echo “Today is “;
echo date(“d F, Y”);
// echo a space before the current time
echo “ “;
?>
<span id=”clockFace” ><?php echo date(“G:i:s”);
?></span>
<p>
// Copy About Wawasan page from http://wou.edu.
my/about_overview.aspx
</p>
<br>
<span style=”font-size:x-small”>The site is
developed by <a href=”mailto:johndoe@nothing.
com”>John
Doe</a></span>
</BODY>
</HTML>
60 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
61UNIT 1
Introduction to web development and PHP
Appendix
Introduction
This appendix introduces you to the general techniques for installing Apache,
MySQL and PHP on the Windows operating system. The installation steps for
the Linux system were covered in section 1.2.
Installing Apache
The Apache web server will be the server hosting the PHP and MySQL components
that you will be using soon. The following guide works for Windows XP SP 3
and above. For other versions of Windows, please read the notes for Win32 at
http://httpd.apache.org.
Installation steps
1. Visit www.apache.org, scroll down and look for the HTTP Server
hyperlink and click on it (Figure 1.27).
Figure 1.27 The HTTP Server hyperlink at www.apache.org
62 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
2. You will arrive at the Apache HTTP Server Project page. Look for the
Apache HTTP Server 2.2 latest and stable releases, usually located on the
second row. Avoid selecting the alpha releases. In this guide, the Apache
HTTP Server 2.2.17 is selected. Click on the Download hyperlink
(Figure 1.28).
Figure 1.28 Download hyperlink of Apache HTTP Server 2.2.17
3. This will take you to the download page. Look for the section entitled
Apache HTTP Server (httpd) 2.2.17 is the best available version” and
select Win32 Binary without crypto (no mod_ssl) (MSI Installer): httpd-
2.2.17-win32-x86-no_ssl.msi (Figure 1.29). At this stage, security is not
our major concern, so it is fine to select the installer without crypto.
Download the MSI Installer to your computer’s hard disk.
Figure 1.29 Win32 Binary without crypto
63UNIT 1
Introduction to web development and PHP
4. Once the download is complete, launch the installer by double-clicking
on its icon. This will bring up the Apache HTTP Server 2.2  Installation
Wizard”.
Figure 1.30 Apache HTTP Server 2.2 Installation wizard
5. Click on Next > to begin the installation process.
Figure 1.31 Apache HTTP Server 2.2 License agreement
64 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
6. You will be shown the License Agreement (Figure 1.31). Select the button
to accept the License Agreement and then click on Next >. You will then be
shown the Read This First” screen. Read it if you want to know more
about Apache.
Figure 1.32 Apache HTTP Server 2.2 Read this first
7. Continue by clicking on Next > and you should arrive at the Server
Information screen (Figure 1.33). Enter the following information:
a. Network Domain: domain_name.com (or something similar)
b. Server Name: testpc.domain_name.com (or something similar)
c. Administrator’s Email Address: admin@domain_name.com (or something
similar)
d. Select the button to install Apache programs and shortcuts for ‘All Users’
so that the server will be available to anyone who arrives at your site.
e. Click on Next > to continue.
65UNIT 1
Introduction to web development and PHP
Figure 1.33 Apache HTTP Server 2.2 Server information
8. Next, select the Setup Type (Figure 1.34). You may choose Custom” so
that you will know in detail the components and features that you are
installing.
Figure 1.34 Apache HTTP Server 2.2 Setup type
66 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
9. You may read the feature description of each component on the “Custom
Setup” screen. Leave the default installation path as it is and click on
Next > to continue.
Figure 1.35 Apache HTTP Server 2.2 Custom Setup
10. You are now ready to install the program. Click on Install (Figure 1.36)
and let the installation process begin.
Figure 1.36 Apache HTTP Server 2.2 Ready to install
67UNIT 1
Introduction to web development and PHP
Figure 1.37 Apache HTTP Server 2.2 Installing
11. When the installation is complete, click on Finish (Figure 1.38).
Figure 1.38 Apache HTTP Server 2.2 Installation completed
68 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Installing PHP
PHP is a widely used general-purpose scripting language that is especially suited for
web development and can be embedded into HTML. The following guide works
for Windows XP SP 3 and above. For other versions of Windows, please read the
notes for Windows systems at http://php.net/manual/en/install.windows.php.
Installation steps
1. Visit www.php.net, look for the downloads hyperlink at the top of the
web page and click on it (Figure 1.39).
Figure 1.39 PHP.net download hyperlink
2. Look for the PHP 5.3 current stable releases. In this guide, we will be
using PHP 5.3.4. Scroll to the Windows Binaries section and click on
http://windows.php.net/download/.
Figure 1.40 PHP.net Windows Binaries
69UNIT 1
Introduction to web development and PHP
3. You will arrive at a download page showing various versions of PHP.
Since we are using Apache 2.2 from apache.org, we will select the VC6 x86
Thread Safe version for non-CGI applications. Click on VC6 x86 Thread
Safe, Zip format.
Figure 1.41 PHP.net VC6 x86 Thread Safe, Zip format
To learn more about the various versions of PHP, please read the
following: “Manual Installation Steps”, http://www.php.net/manual/en/
install.windows.manual.php
4. Save the zip file to your local disk. Then, unzip the package with any
standard unzip program. We recommend you unzip the package to C:\
and rename it ‘C:\php’. Be careful not to insert spaces in between the
directory name to avoid the web server string concatenation problem.
5. The next step is to set up a valid configuration file for PHP, ‘php.ini’.
Go to ‘C:\php’ and look for the file named ‘php.ini-development’.
There are two ‘ini’ files distributed in the zip file, ‘php.ini-production’
and ‘php.ini-development’ (Figure 1.42). The ‘php.ini-production’ file is
optimised for performance and security. For the purposes of learning,
you will be using the ‘php.ini-development’ file for simplicity and fewer
configuration steps. You can switch to ‘php.ini-production’ once you are
more familiar with PHP. Therefore, rename ‘php.ini-development’ as
‘php.ini’.
70 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
Figure 1.42 Renaming php.ini-development as php.ini
6. Next, you will make a copy of the ‘php.ini’ file (Figure 1.43) and place
it in the ‘C:\WINDOWS’ directory so that Apache can find it.
Figure 1.43 Copy the php.ini file into C:\WINDOWS
71UNIT 1
Introduction to web development and PHP
7. Finally, you need to copy the ‘php5ts.dll’ file (since we are using PHP
version 5) from ‘C:\php’ into the ‘C:\Program Files\<Apache Group>\
<Apache Version>\bin’ directory, which is named ‘C:\Program Files\
Apache Software Foundation\Apache2.2\bin’ in this case.
Figure 1.44 Copy php5ts.dll from C:\php into the <Apache Version>\bin
directory
You have now completed the installation of both Apache and PHP on the
Windows system. Next, you are going to configure Apache and PHP.
Configuring Apache and PHP
At this point, the Apache web server should already have been installed on your
computer. You should be able to see the “Apache Service” taskbar icon (Figure 1.45)
at the lower right-hand corner of your Windows desktop screen if you had
accepted all the default installation features.
Figure 1.45 Apache Service taskbar icon
72 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
If you cannot see the icon, the Apache service can be accessed via the Start menu or
from the program installation directory, which by default is at ‘C:\Program Files\
Apache Software Foundation\Apache2.2\bin’.
Figure 1.46 The Apache service can be accessed via the Start menu
Once you have confirmed that the Apache service is running, you can test the
Apache server by entering http://localhost in the web browser. If the installation
was successful, you will be able to see the default Apache page with the “It works!”
headline. If this web page is not displayed, visit the ‘error.log’ file located in the
‘C:\Program Files\Apache Software Foundation\Apache2.2\logs’ folder to see what
went wrong with your installation. The setup may fail if Apache is trying to share
HTTP port 80 with another web server, such as Windows IIS, or an application,
such as a firewall.
Figure 1.47 Test the Apache installation with http://localhost
After verifying that your Apache installation works fine, you then need to add
some code to the configuration file, ‘httpd.conf ’, which can be found in the ‘C:\
Program Files\Apache Software Foundation\Apache2.2\conf’ folder, before you
can run PHP. This file can be opened with any text editor, for instance Notepad.
You are advised to make a backup copy of the ‘httpd.conf file before you start
making any modifications to it.
73UNIT 1
Introduction to web development and PHP
Configuring Apache to recognise PHP files
1. Go to the ‘C:\Program Files\<Apache Group>\<Apache Version>\conf
directory, which is ‘C:\Program Files\Apache Software Foundation\
Apache2.2\conf’ in this case. Make a copy of the ‘httpd.conf ’ file and
name it ‘httpd.conf.backup’.
Figure 1.48 Create a backup copy of httpd.conf
2. Open ‘httpd.conf with a text editor like Notepad. Use the text editor
to find the “LoadModule” section. Scroll to the end of the “LoadModule”
section and add the following code after the last #Lo ad Mod ul e line
(Figure 1.49).
#Insert the following to set up the PHP 5 module for
Apache 2.2.
#Make sure your path matches the location of this file.
LoadModule php5_module “c:/php/php5apache2_2.dll
Figure 1.49 Adding the LoadModule code to httpd.conf
3. Note that the words followed by the hash character, “#” are interpreted
as comments and they will not be executed. Please make sure the path
‘php5apache2_2.dll’ matches the location of the existing file.
74 WAWASAN OPEN UNIVERSITY
TCC 242/05 Web Database Application
4. Next, find the “AddType” section. Scroll to the end of the “AddType” section
and add the following code after the last line of this section.
# In order for Apache to recognise a PHP file as one that
needs to be
# parsed with the PHP engine, you need to add the following
two lines
AddType application/x-httpd-php .php
# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps
Figure 1.50 Adding the AddType code to httpd.conf
5. Save the changes you made to ‘httpd.conf and close the file. Launch the
Apache Service Monitor (Figure 1.51) from the Apache Service taskbar
icon by right clicking on the icon and then selecting Open Apache
Monitor. You can also launch the Monitor from the start > All Programs
menu if you did not install the taskbar icon.
Figure 1.51 The Apache Service Monitor
75UNIT 1
Introduction to web development and PHP
6. Select Apache 2.2 and then click the Restart button. Note that after
you restart the service, there will be a “PHP/5.3.4” label shown next to
the “Apache/2.2.17 (Win32)” label at the bottom left-hand side of the
monitor window (Figure 1.52). This shows that you have successfully
configured Apache with PHP. If not, check for errors and revisit the
steps above.
Figure 1.52 An additional “PHP/5.3.4” label situated next to the “Apache/
2.2.17 (Win32)label indicates that you have successfully configured
Apache with PHP
Once Apache is configured to recognise PHP, you can test a PHP script. By
default, the document root directory for Apache is the ‘C:\Program Files\<Apache
Group>\<Apache Version>\conf ’ directory, which is ‘C:\Program Files\Apache
Software Foundation\Apache2.2\htdocs’ in this case. Note that you can change the
document root directory path in the ‘httpd.conf ’ file under the “DocumentRoot”
section.
Let us now use the default document root directory (‘C:\Program Files\Apache