Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Institut Universitaire et Stratégique de l’Estuaire

Estuary Academic and Strategic Institute (IUEs/Insam)


Sous la tutelleacadémique des Universités de Dschang et de Buéa.

LECTURE NOTES ON WEB PROGRAMMING 2

Academic Year: 2022/2023

Specialty: software engineering level II

COURSE FACILITATOR: Mr. FOTSO ALAIN

Page 1 of 76
General objectives

Upon completing this course, the student should be able to


 Differentiate between a static and dynamic web site
 Understand and write programs in PHP programming Language
 Design dynamic web page using PHP to link to a MYSQL database
 Write SQL Query associate with PHP to manipulate data in a MYSQL database
 State other competitors of PHP and MYSQL

Specific objectives

 Understand the use and importance of PHP


 Master PHP syntax and variables
 Make use of PHP conditional and repetitive structure

INTRODUCTION

The PHP language was precisely designed to create "living" sites (we speak of
dynamic web sites). In addition, if you want to learn how to create dynamic websites
yourself, now is your lucky day: you are on a course for real beginners in PHP! The
main thing is to read the entire chapters in order. Afterwards, it goes by itself and you
will soon be amazed at what you are able to do!

What makes the web so successful today is both its simplicity and its ease of access.
A simple Internet user does not need to know "how it works behind". In addition, luckily
for him. On the other hand, a webmaster apprentice like you must, first of all, know the
basics of how a website works. What is a server and a client? How do you make your
site dynamic? What do PHP and MySQL mean? This first chapter is here to answer all
these questions and show you that you are capable of learning how to create dynamic
websites. All readers will be reassured in the end that they are starting at the same
level!

Static and dynamic sites

We consider that there are two types of websites: static sites and dynamic sites. Static
sites: these are sites created only using HTML and CSS. They work very well but their
content cannot be updated automatically: the owner of the site (the webmaster) must
modify the source code to add new features. This is not very practical when you have

Page 2 of 76
to update your site several times in the same day! Static sites are therefore well suited
to creating "showcase" sites, for example to present your company, but without going
further. This type of site is becoming increasingly rare today, because as soon as we
add an element of interaction (such as a contact form), we no longer speak of a static
site but of a dynamic site.

Dynamic sites: more complex, they use other languages in addition to HTML and
CSS, such as PHP and MySQL. The content of these websites is said to be "dynamic"
because it can change without the intervention of the webmaster! Most of the websites
you visit today, including Site du Zéro, are dynamic sites. The only prerequisite for
learning how to create this type of site is to already know how to create static sites in
HTML and CSS.

The objective of this course is to enable you to build dynamic websites entirely on your
own, step by step. Indeed, these can offer much more exciting features than static
sites. Here are some elements that you will be able to create: a members area: your
visitors can register on your site and have access to sections reserved for them; a
forum: it is common today to see websites offer a discussion forum to help each other
or simply pass the time; a visitor counter: you can easily count the number of visitors
who connected to your site during the day, or even know the number of visitors
browsing it! news: you can automate the writing of news, offering your visitors the
possibility to write, comment, etc. ; a newsletter: you can send an e-mail to all your
members regularly to present them the news and thus encourage them to come back
to your site. Of course, these are just examples. It is possible to go even further, it all
depends on your needs. Know for example that almost all online gaming sites are
dynamic. In particular, there are virtual animal breeding sites, space conquest games,
etc.

When you want to visit a website, you type its address into your web browser, be it
Mozilla Firefox, Internet Explorer, Opera, Safari, or whatever. But have you ever
wondered how the web page gets to you? You should know that the Internet is a
network made up of computers. These can be classified into two categories. Clients:
These are the computers of Internet users like you. Your computer is therefore part of
the client category. Each customer represents a visitor to a website. In the following
diagrams, a customer's computer will be represented by the following image. Servers:
these are powerful computers that store and deliver websites to Internet users, that is
Page 3 of 76
to say to customers. Most Internet users have never seen a server in their life. Yet
servers are essential to the proper functioning of the Web. In the next diagrams, a
server will be represented by the image in the following figure.

We summarize: your computer is called the client, while the computer that owns the
website is called the server. How do the two communicate? This is precisely where the
difference between a static site and a dynamic site is made. Let’s see together what is

changing.

Case of a static web site


When the site is static, the scheme is very simple. This happens in two stages, as you
can see in the following figure: 1. the client asks the server to see a web page; 2. the
server responds by sending it the requested page.

Communication is therefore rather basic: “Hello, I am the customer, I would like to see
this web page. "Here is the page you asked for." »On a static site, nothing else

Page 4 of 76
happens. The server stores web pages and sends them to clients who request them
without

Case of a dynamic web site

When the site is dynamic, there is an intermediate step: the page is generated
(following fig.). The client asks the server to see a web page; the server prepares the
page especially for the client; the server sends it the page it has just generated.

The web page is generated each time a customer requests it. This is precisely what
makes dynamic sites alive: the content of the same page can change from moment to
moment. This is how some sites manage to display, for example, your nickname on all
pages. Since the server generates a page each time it is asked for one, it can
customize it according to the tastes and preferences of the visitor (and display, among
other things, his nickname). Languages of the Web When you create a website, you
have to manipulate not one but several languages. As a webmaster, it is imperative to
know them.

For the static web site


Many languages have been created to produce websites. Two of them constitute an
essential base for all webmasters. HTML: it is the language at the base of websites.
Easy to learn, it works from beacons. Here is an example of HTML code:

CSS: is the formatting language for websites. While HTML allows you to write the
content of your web pages and structure them, CSS takes care of formatting and
layout. It is in CSS that we choose in particular the color, the size of the menus and
many other things.

Page 5 of 76
Languages are the basis of all websites. When the server sends the web page to the
client, it is actually sending code in HTML and CSS. The problem is that when you only
know HTML and CSS, you can only produce static sites… and not dynamic sites! For
the latter, it is necessary to manipulate other languages in addition to HTML and CSS.
So the question to ask yourself is: do you know HTML and CSS? If so, that's fine, you
can continue as we'll need it later. If the answer is no, don't panic. These languages
are not very difficult, they are accessible to all. You can learn them by reading my
course on HTML and CSS. Note that learning these languages only takes a few short
weeks, or even less if you have enough free time.

For the dynamic web site


Whatever website you want to create, HTML and CSS are therefore essential.
However, they are not enough to make dynamic sites. They must be supplemented
with other languages. This is precisely the purpose of this course: you will learn how
to use PHP and MySQL to create a dynamic website. PHP: it is a language that only
servers understand and which makes your site dynamic. It is PHP which "generates"
the web page as we saw on one of the preceding diagrams. This will be the first
language we will discover in this course. It can work on its own, but it only really gains
interest when combined with a tool like MySQL.

MySQL: this is called a DBMS (Database Management System). To put it simply, its
role is to record data in an organized way to help you find it easily later. It is thanks to
MySQL that you will be able to save the list of members of your site, the messages
posted on the forum, etc. The language used to communicate with the database is
called SQL

PHP can work on its own and is enough to create a dynamic site, but things get really
interesting when combined with a DBMS like MySQL. However, for the sake of
simplicity, let's forget about MySQL for now and focus on PHP.

Clients are unable to understand PHP code: they only know HTML and CSS. Only the
server is able to read PHP. The role of PHP is precisely to generate HTML code (we
can also generate CSS, but this is rarer), code which is then sent to the client in the
same way as a static site, as shown in fig. next.

Page 6 of 76
PHP is a programming language used on many servers to make decisions. PHP decides what
HTML code will be generated and sent to the client each time.
To understand the interest of all this, let us take an example. We can write in PHP: “If the visitor
is a member of my site and his name is Jonathan, displays welcome Jonathan on the web page.
On the other hand, if it is not a member of my site, displays Welcome instead and invites the
visitor to register. This is a very basic example of a dynamic site: depending on whether you
are a registered member or not, you will not see the same things and may not have access to all
sections.

And the competition?

HTML and CSS have no competition because they are standards. Everyone is expected to know
about them and use them on all websites. On the other hand, when it comes to dynamic sites,
PHP and MySQL are far from the only ones on the spot. I can't give you a complete list of their
competition, that would be way too long (and boring!). However, for your general knowledge,
you should at least know a few other big names. First, if we often tend to combine PHP and
MySQL to create powerful dynamic sites, we should not mix the two. The first has different
competitors from the second.
Among the competitors of PHP, we can mention the following:

1. ASP .NET: designed by Microsoft, it exploits the framework (that is to say a set of
libraries that provide services for developers) .NET . This language can be interesting
if you are used to developing in C # .NET and you don't want to be disoriented.
2. Ruby on Rails: very active, this framework is used with the Ruby language and allows
you to create dynamic sites quickly by following certain conventions.
3. Django: it is similar to Ruby on Rails, but it is used in Python language.
4. Java and JSP (Java Server Pages): more commonly called "JEE", it is particularly used
in the professional world. It requires a certain rigor. The establishment of a JEE project
is traditionally a little longer and heavier, but the system is appreciated by
Page 7 of 76
professionals and institutions. This is what is used on the French taxes website,
for example.

I cannot present all the competitors here, but it should already give you a good idea. For

information, it is also possible to use for example the C language or C ++, although this is more

complex and not necessarily always very suitable (in plain language, I do not recommend it at

all).

Which one to choose from the list then? Which is the best?

Given the purpose of this course, you would expect me to instantly answer "PHP!" ".

However, no. In fact, it all depends on your programming knowledge. If you have already

worked with Java, you will quickly be comfortable with JSP. If you are familiar with Python,

Django might be right for you.

As for PHP, it stands out from its competitors by having a large community that can help you

quickly on the Internet if you have any problems. It is an easy to use language, ideal for

beginners as well as for professionals: Wikipedia and Facebook are examples of famous and

very frequented sites which run on PHP.

In short, there is no better choice. I recommend the language where you can be sure you have

someone to help you. PHP in this sense is often a very good choice.
MySQL competitors
When it comes to databases, the choice is again very vast. However, while PHP and its
competitors are mostly free and free, most DBMSs are not. Among the competitors of MySQL,
I advise you to know (at least by name) the following:
1. Oracle: it is the most famous, the most complete and the most powerful DBMS. It is
unfortunately not free (and expensive), which rather reserves it for companies that
already use it heavily. There are, however, free versions of Oracle, especially for those
who want to learn how to use it.
2. Microsoft SQL Server: Published by Microsoft, it is often used in combination with
ASP .NET, although it can be used with any other language. It is paid, but there are
limited free versions.

Page 8 of 76
3. Postgre SQL: this is a free open source DBMS like MySQL, which offers more
advanced features. Sometimes compared to Oracle, however, it still has some way to
go. It has a somewhat smaller community than MySQL and Oracle. The open classroom
web site uses PostgreSQL.

Again, this list is far from exhaustive but introduces you to at least some big names. For

information, MySQL remains by far the most widely used free and open source DBMS. Among

the paid professional solutions, Oracle is the most advanced and the most widespread, but its

use is mainly reserved for large companies. At the end of the day, if your means are limited,

you don't have much of a choice for the DBMS. MySQL is the best choice because it is open

source, free, powerful, and used by many people who can help you.

Many combinations are possible

As you have seen, you have the choice between many tools to create a dynamic site. Most of

them are free. Note that you can a priori combine these tools as you see fit. For example, we

can very well use PHP with a database other than MySQL, such as Oracle or PostgreSQL.

Likewise, MySQL can be used with any other language: Java, Python, Ruby, etc. However, the

combination "PHP + MySQL" is probably the most common. It is no coincidence that this

course deals with these two proven tools.

Conclusion

There are two types of websites: static sites: produced in HTML and CSS, their content can

only be updated by the webmaster; dynamic sites: made with other tools like PHP and MySQL

in addition to HTML and CSS, they allow visitors to participate in the life of the site, to post

messages… in short, to bring the site to life! Visitors to the site are called customers. They ask

the server that hosts the site to transmit the web pages to them. PHP is a language executed by

the server. It allows you to personalize the page according to the visitor, to process their

Page 9 of 76
messages, to perform calculations, etc. It generates an HTML page. MySQL is a database

management system. It is responsible for storing information (list of messages, members, etc.).

Preparing the computer

For the dynamic website

We now know that PHP is running on the server and that its role is to generate web

pages. However, only a server can read PHP; however, your computer is not a server.

How are you going to be able to create a dynamic site if PHP is not working for you?

Never mind: we will temporarily turn your computer into a server so you can run PHP

and work on your dynamic site. You will be all set to program after reading this chapter!

What programs do we need? Depending on whether you create a static site or a

dynamic site, you need different software. In fact, making a dynamic site unfortunately

requires some additional software for us! With a static site Webmasters who create

static sites with HTML and CSS are lucky, they usually already have all the programs

they need. A text editor: in theory, a program such as Notepad that comes with

Windows is sufficient, although it is recommended to use a slightly more advanced tool

such as Notepad ++. We'll talk about editor's choice again at the end of this chapter. A

web browser: it allows you to test the web page. You can use, for example, Mozilla

Firefox, Internet Explorer, Google Chrome, Opera, Safari, or any other browser you

are accustomed to when going on the web. It is advisable to test your site regularly on

different browsers.

For the dynamic website

In order for your computer to read PHP, it must behave like a server. Rest assured,

you don't need to buy a special machine for this: you just need to install the same

Page 10 of 76
programs that are found on the servers that deliver websites to Internet users. These

programs that we are going to need, what are they? Apache: this is called a web server.

This is the most important of all programs, as it is responsible for delivering web pages

to visitors. However, Apache only supports static websites (it can only process HTML

pages). It must therefore be supplemented with other programs. PHP: it is a plug-in for

Apache which allows it to process dynamic web pages in PHP. Clearly, by combining

Apache and PHP, our computer will be able to read web pages in PHP. MySQL: this

is the database management software I told you about in the introduction. It allows you

to save data in an organized way (like the list of members of your site). We won't need

it immediately, but we might as well install it now.

All elements that will help us create our dynamic site are free and open. Of course, there are

others (sometimes paying), but the Apache + PHP + MySQL combination is the most common

on web servers, so much so that we have created ready-made “packs” that contain all these

elements. It is possible to install them one by one but it takes longer and you will not gain

anything (unless you are a server administrator, which should not be your case;)).

In the rest of this chapter, we will see how to install the "pack" that is appropriate for your

operating system.

For Windows: WAMP There are several ready-made packages for Windows. I suggest

you use WAMP Server, which has the advantage of being regularly updated and

available in French. Start by downloading WAMP here. Once downloaded, install it

leaving all options at default. It should install in a directory like C: \ wamp and create a

shortcut in the Start menu. When you launch WAMP, an icon should appear at the

bottom right of the taskbar, next to the clock, as in the following figure. WAMP icon If

Page 11 of 76
a window appears telling you that the firewall is blocking Apache, click on Allow access

(following figure). You have no reason to worry, this is perfectly normal.

MODULE 2: HTML5 AND CSS Essentials


Specific Objectives
By the end of this lesson, you will be able to:
 Consider HTML5 development skills you can apply to both traditional and
nontraditional delivery platforms, including mobile apps.
 Identify the Web development trifecta and explain its significance.
 Explain the evolution of HTML and its relevance to modern design techniques.
 Create and deploy HTML5 structure tags.
 Perform HTML5 code validation, which includes explaining the practical value of
 code validation and listing the steps to validate HTML5 code.
 Explain the importance of universal markup creation.
 Apply the HTML5 <video> element appropriately.
 Use the HTML5 <audio> element.
 Define common elements of HTML5 application programming interfaces (APIs).

Introduction to HTML5 and CSS3


The skills of Web page and app creation have become vital to many careers. If you are
software engineer or with webmaster, then you are likely to need skills with Web-based app
technologies for various job-related tasks. If you want to work as a Web developer, app
developer or site designer, with responsibility for the Web resources of an entire company
or organization, then you need to master the most current standard languages for Web
authoring: Hypertext Markup Language version 5 (HTML5) and Cascading Style Sheets
version 3 (CSS3).

Migration to Mobile Devices


Consider that mobile computing now means more than just being able to check e-mail

Page 12 of 76
and Web pages on the move from a mobile device. Today, users also move from one mobile
environment to another, using a variety of Web-enabled devices from various companies that
use different computing platforms.
The principle of responsive design is essential for today's user interface (UI) designers.
The term "responsive design" describes the ability to create pages that respond to user
screen size and that work in multiple environments. You will learn about responsive
design techniques later in this course.
Users no longer view Web pages only through standard Web browsers. Your smartphone,
tablet, smart TV and gaming console are all capable of reading Web-based markup
languages (Figure 1-1).

As a designer, it is your responsibility to ensure that your pages render as your audience
expects, regardless of the device used to access them. Therefore, your code must work in
many different environments without requiring a different solution for each one. HTML5
and CSS3 allow most devices to properly render the code, regardless of the size of the
device’s screen.
Consider the HTML5 and CSS3 technologies as an attempt to develop a "one size

Page 13 of 76
fits all" page development solution for all devices. However, this approach does

not work in all situations. You must determine when it makes sense, and when it

does not.

App development

The term "app" has become widely used to describe relatively small applications developed
exclusively for mobile devices. Smartphones and tablets created a huge market for apps. Many
organizations now have an app for download in Google Play™, the Windows Store and the
Apple App Store. HTML5 and CSS3 are capable of creating both apps and Web pages.

The Web Development Trifecta

The future of Web design and app development will be ruled by three technologies: HTML5,

Cascading Style Sheets (CSS) and JavaScript (see Figure 1-4). Used together, these technologies
create Web pages that easily adapt to smartphones, tablets, gaming devices and smart TVs,
as well as to traditional computers.

HTML5, CSS and JavaScript as a group are sometimes called the "HTML5 family" or the

"Web development trifecta." Table 1-1 explains the functions of each technology.

Page 14 of 76
The Evolution of HTML5

As you should already know, HTML creates and links one document to another via pointers
called

hyperlinks. A hyperlink is a set of instructions embedded within a file that calls another
location in the file or a separate file when the link is clicked. The global set of linked documents
across the existing Internet framework grew into what is known as the World Wide Web.

Hypertext Markup Language (HTML)

Web pages are created using Hypertext Markup Language (HTML). HTML is the markup
language that defines page structure, hyperlinks, graphics and more to enable pages to render
in Web browsers and other devices. The W3C regulates the development of HTML and CSS
standards

The World Wide Web Consortium (W3C) is an international community where Member
organizations, a full-time staff, and the public work together to develop Web standards. Led by Web
inventor and Director Tim Berners-Lee and CEO Jeffrey Jaffe, W3C's mission is to lead the Web
to its full potential.

HTML is an evolving language. It doesn’t stay the same for long before a revised set of
standards and specifications are brought in to allow easier creation of prettier and more
efficient sites. Let’s start at the beginning...

HTML 1.0

HTML 1.0 was the first release of HTML to the world. Not many people were involved in
website creation at the time, and the language was very limiting

Page 15 of 76
HTML 2.0

HTML 2.0 included everything from the original 1.0 specifications but added a few new
features

HTML 3.0

More and more people were getting into the HTML game around now, and while the previous
standards offered some decent abilities to webmasters (as they became known), they thirsted
for more abilities and tags. They wanted to enhance the look of their sites.

HTML 3.2

The browser-specific tags kept coming, and it became increasingly apparent that a standard
needed to be found. To this end, the » World Wide Web Consortium (abbreviated to the W3C)
was founded in 1994 to standardize the language and keep it evolving in the right direction.
Their first work was code-named WILBUR, and later became known as » HTML 3.2.

HTML 4.01

HTML 4.0 was a large evolution of the HTML standards, and the last iteration of classic HTML.

XHTML

Extensible HTML (XHTML) is a version of HTML that incorporates the strict syntax rules of
Extensible Markup Language (XML) with the existing set of HTML 4.01 tags to create Web
documents. Like HTML 4.01, XHTML has three flavors: Transitional, Strict and Frameset.

XHTML introduced syntax rules that must be followed in order for a document to

validate, including the following:

• The XHTML DOCTYPE statement is required.

• Document structure tags are required.

• The document must have one root element.

• All elements and attributes must be typed in lowercase letters.

• Each element must be properly closed, either with a separate closing tag or with a

closing backslash (\), as appropriate.

• All elements must be properly nested.

Page 16 of 76
• Attribute values must be enclosed in quotation marks.

The W3C Recommendation for XHTML was published in 2000. The goal for XHTML is to
provide a bridge of backward- and forward-compatibility for HTML documents to easily adapt
to XML technologies in future use. Many developers upgraded their Web page code from
HTML to XHTML by applying the stricter syntax to existing code.

HTML5

HTML version 5 (HTML5) is the latest version of HTML under development by the W3C.

The W3C has created an HTML5 logo, shown in Figure 1-6, to market the technology.

HTML5 provides modern design techniques for the Internet while requiring fewer plugins.

For example, HTML5:

• Standardizes how video and audio are presented on a Web page.

• Introduces the <video> element, which is designed to eliminate the need to install third-
party plug-ins (such as those for Adobe Flash or Microsoft Silverlight).

• Adds the <audio> element, which allows pages to seamlessly add audio files for events such
as podcasts.

• Establishes ways to enable drag-and-drop capability for Web pages without using third-
party add-ons.

Page 17 of 76
• Gives developers more native tools to use on a page, such as download progress indicators,
image captioning options and form validation.

• Provides developers with a native option for offline storage, and enables applications to run
as expected even without network connectivity.

• HTML5 allow most devices to properly render the code, regardless of the size of the device’s
screen.

• Allows developers to retrieve the geographical location information for a Web site visitor.
This technology is called geolocation. Examples include using the global positioning system
(GPS) of a mobile device to determine the device's location, which allows Web services to be
provided based on the client's location.

HTML5 Structure Elements

HTML5 with CSS provides an effective and simple way to structure Web pages. The developers
of HTML5 created specific elements to define the document structure. These elements
include <header>, <footer>, <main>, <nav>, <section>, <article> and <aside>,

Page 18 of 76
As the figure illustrates, a developer can structure the Web page with basic elements that are
easily interpreted and native to any HTML5-compliant browser, regardless of whether the
browser is on a mobile device, laptop or tablet. Table 1-2 describes the HTML5 page structure
elements.

These HTML5 basic structure elements may or may not render in older browsers that do not
support HTML5, such as Internet Explorer versions prior to IE9. This should not hinder your
use of HTML5 structure tags, but you should be aware of it

The <video> Element

In this section, you will learn to add video to a Web page using the HTML5 <video> element.

Page 19 of 76
Suppose your supervisor asks you to provide a step-by-step instructional video in your
company Web site that customers can access from anywhere. The video must be able to
play on all smartphones, tablets, desktop computers and gaming consoles that have an
HTML5-compliant browser. No plug-ins can be required to view it.

HTML5 has introduced the <video> element to provide developers with a standard method to
embed video into their Web pages (see Figure 1-12). Prior to the <video> element, end-users
needed browser plug-ins (such as Adobe Flash, Microsoft Silverlight or Apple QuickTime) in
order to view video. Not all browsers or devices support these plug-ins, so a standardized way
to include video was needed.

Embedding video in an HTML5 document is straightforward. See the following code:


<video width="360" height="270" controls="controls" poster="image.png">
<source src="video.mp4" type="video/mp4" />
<source src="video.webm" type="video/webm" />
<source src="video.ogg" type="video/ogg" />
Your browser does not support the HTML5 video element.
</video>

Page 20 of 76
Table 1-3 describes the elements and attributes used in this example code.

Multiple sources can be identified with the <source> element to ensure various video formats
are supported. The HTML5 specification does not require a video codec to be supported by
all user agents, but it does support the following formats:
• MPEG-4 (MP4)— generally uses the H.264video codec, which is native to most
browsers that support HTML5. This codec uses far less processor and battery power
because it does not require a plug-in. YouTube recently reformatted most videos away
from Flash (which requires a plug-in) to MP4.
• WebM— generally uses the VP8 codec, which is an open video compression format
owned by Google.
• Ogg— uses the Theora format for HTML5 video, which is a free video compression format
that can be distributed without licensing fees to ensure all browsers and devices can access
your video, you should format your video files to all three of these formats and identify them

Page 21 of 76
in the <source> element. If that is not possible, then choose one (such as the MP4 format) as
the default format.

The <audio> Element


Similar to the <video> element, HTML5 has introduced the <audio> element to provide
developers with a standard method to embed audio into Web pages (see Figure 1-14).
Prior to the <audio> element, end-users needed browser plug-ins or separate applications
(such as Windows Media Center, Apple iTunes, Apple QuickTime, Adobe Flash and Microsoft
Silverlight) to listen to audio in Web pages. Not all browsers or devices supported these plug-
ins, so a standardized way to include audio was needed.

Embedding audio in an HTML5 document requires the following code:


<audio controls="controls">
<source src="media/audio.mp3" type="audio/mpeg" />
<source src="media/audio.wav" type="audio/wav" />
<source src="media/audio.ogg" type="audio/ogg" />
Your browser does not support the HTML5 audio element.
</audio>
As with the <video> element, the controls attribute identifies the default audio controls:
Play, Pause, Volume, etc. Any text enclosed within the <audio> element will appear in
browsers that do not support it.

Page 22 of 76
Like the <video> element, the <audio> element allows you to identify multiple sources with
the <source> element to ensure various audio formats are supported. The HTML5
specification does not require a specific audio codec to be supported, but it does support three
audio formats:
• MP3
• WAV
• Ogg

Not all HTML5-compliant browsers support all of these audio formats. Table 1-4 lists the
HTML5 audio formats and shows which HTML5-compliant browsers support each format.
(Information is current at the time of this writing.)
Table 1-4: HTML5-compliant browser support for HTML5 audio formats

In addition to the controls attribute, several other attributes are common to both the <video>
element and the <audio> element. Table 1-5 describes two widely used attributes.
Table 1-5: Additional <audio> and <video> attributes

In the following lab, you will add audio to a Web page using the HTML5 <audio> element.
Suppose your supervisor asks you to embed an audio tour into your company Web site.
The audio must be able to play on any device with an HTML5 browser, without requiring
any plug-ins.

Page 23 of 76
HTML5 APIs
The future of Web development will probably focus on HTML5 APIs. An application
programming interface (API)is a source code specification that enables components of an
application or program to work together to produce the desired functionality. HTML5
APIs provide an open environment for developing Web applications that does not rely on
proprietary browser plug-ins.
HTML5 APIs consist of the trifecta technologies: HTML5, CSS and JavaScript. These
technologies are used together to provide Web pages that can easily adapt to
smartphones, tablets, gaming devices and smart TVs, as well as to traditional desktop
computers.
HTML5 APIs are also used to create apps for mobile devices, not just Web pages
Some functions of the HTML5 APIs include:
• Media (audio and video).
• Document editing.
• Cross-document messaging.
• MIME type and protocol handler registration.
• Web storage
Popular APIs
API (Application Programming Interface) are way to create applications using pre-builds components

The Canvas API


The Offline AppCache API
The Geolocation API

The HTML geolocation feature enables your web application to obtain the
geographical position of your website visitors.
The Drag-and–Drop API

From HTML5 it is possible to drag and drop HTML elements inside an


HTML page. Via JavaScript event listeners, you can decide what happens
when the user drags and drops elements.
The File API

Page 24 of 76
The HTML5 file API enables JavaScript inside HTML5 pages to load and
process files from the local file system.
The History API

The HTML5 history API gives you access to the browser navigation history
via JavaScript

Other popular APIs include Offline Apache, Geolocation, Canvas and Drag-and-Drop.
You will study these APIs in detail later in the course.
Summary
HTML5 implementations are spreading quickly as organizations and users adopt mobile
devices for work and play.
Think of five Web sites that you visit frequently. Are they HTML5 sites? To find out, view
the source code of the page and view the DOCTYPE declaration. Is the DOCTYPE
declaration written simply as follows?
<!DOCTYPE html>
If so, then you are looking at an HTML5 page.
Note that the DOCTYPE declaration is not required for HTML5, but it is good practice to
include it for older HTML standards to tell the browser which version of HTML to expect.
It is almost always written in uppercase letters by Web developers because older versions
of HTML require this case-specificity.

Assessment Questions
1. The terms "HTML5 family" and "Web development trifecta" are sometimes used to
refer to which combination of Web technologies?
a. HTML5, CSS3 and JavaScript
b. HTML5, XML and CSS3
c. HTML5, JavaScript and Flash
d. HTML5, Flash and XML
2. Which HTML5 structure element was designed to enclose Web site content such as
company services, blogs, images and videos?
a. <header>
b. <footer>

Page 25 of 76
c. <article>
d. <aside>
3. Which element introduced in HTML5 saves mobile device resources by avoiding the
use of plug-ins to play MP4 files? <video> element
4. What are reasons to justify the use of HTML5?
It gives developers more tools to use on web page
It permits offline storage
It provides the use of applications without network connection
It provides responsive design.
5. What is the primary benefit of the HTML5 <video> element?
It eliminates the need to install the third party plug-ins.
6. How is the HTML5 <article> structure element used in a Web page?
It defines site content accompanying the main content.
7. Why should you always validate your code before publishing your Web pages?
If you don’t validate your code, it will suffer from errors or poor traffic owing.

Practical Assessments

1. In the index.html file, insert the following structure elements (shown in bold) exactly
as written. Be sure to close your tags properly.
<!DOCTYPE html>
</head>
<body>
<header>
<img src="media/logo.png" alt="Habitat for Humanity logo" />
</header>
<nav>
<h4>Simple, decent, affordable housing</h4>
<ul>
<li><a href="http://www.habitat.org/how/about_us.aspx">Learn more</a></li>
<li><a

Page 26 of 76
href="http://www.habitat.org/getinv/volunteer_programs.aspx">Volunteer</a></li
>
<li><a href="http://www.habitat.org/gov">Advocate</a></li>
<li><a
href="https://www.habitat.org/cd/giving/donate.aspx?r=r&amp;link=1">Donate</a>
</li>
</ul>
</nav>
<article>
<h1>Our Mission</h1>
<p>Habitat for Humanity believes that every man, woman and child should have a
decent, safe and affordable place to live. We build and repair houses all over
the world using volunteer labor and donations. Our partner families purchase
these houses through no-profit, no-interest mortgage loans or innovative
financing methods.</p>
<imgsrc="media/menu_icon_default.jpg" width="212" height="121"
alt="Silhouettes of Habitat for Humanity workers" />
</article>
<article>
<h1>Why We Build</h1>
<p>There are nearly 2 billion people around the world who live in slum housing
and more than 100 million are homeless. Families left homeless by natural
disasters, war and civil unrest often face dire housing situations as they
struggle to rebuild their lives. We provide shelter and housing assistance to
help these families recover.</p>
</article>
<article>
<h1>Advocacy in Action</h1>
<p>Volunteer Amy Miles lends her voice in support of Habitat's advocacy
efforts and Global Village trips. Use the audio controls below to hear her
stories.</p>
</article>

Page 27 of 76
<aside>
<h4>Build Your Community</h4>
<a
href="http://www.habitat.org/youthprograms/ages_14_25/ages_14_25_default.aspx"
><imgsrc="media/YP3_14to25.jpg" alt="Habitat for Humanity logo"/></a>
<p><a
href="http://www.habitat.org/youthprograms/ages_14_25/ages_14_25_default.aspx"
>Start today</a> to become the leaders of Habitat tomorrow! </p>
</aside>
<footer>
<a href="http://www.habitat.org/how/"> Learn About Habitat</a> |
<a href="http://www.habitat.org/intl/">Where We Build</a> |
<ahref="http://www.habitat.org/support/default.aspx">Support Habitat</a> |
<a href="http://www.habitat.org/stories_multimedia/">Stories and
Multimedia</a><br/><br/>
<p>&#169;2014 Habitat for Humanity&#174; International. All rights reserved.
"Habitat for Humanity&#174;" is a registered service mark owned by Habitat for
Humanity International. Habitat&#174; is a service mark of Habitat for
Humanity International. </p>
</footer>
</body>
</html>

2.Once you have inserted the structure elements, save your changes.
3. Now, open index. htmin a Web browser by right-clicking the file, selecting Open
With, and choosing an HTML5-compliant browser. It should resemble Figure 1-9 bellow.

Page 28 of 76
Page 29 of 76
4. insert the following in your web page
A. Two video files
B. Two audio
C. Two word files
D. Two pdf files

Page 30 of 76
JavaScript Basics
What is JavaScript?

Javascript is a dynamic computer programming language. It is lightweight and most commonly used
as a part of web pages, whose implementations allow client-side script to interact with the user and
make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in Netscape
2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.

Client-Side JavaScript

Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need not be a static HTML, but can include programs that interact with the
user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address
in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other
actions that the user initiates explicitly or implicitly.

Advantages of JavaScript

The merits of using JavaScript are:

• Less server interaction: You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.

• Immediate feedback to the visitors: They don't have to wait for a page reload to
see if they have forgotten to enter something.

Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.

Page 31 of 76
• Richer interfaces: You can use JavaScript to include such items as dragand-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features:

• Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.

• JavaScript cannot be used for networking applications because there is no such support
available.

• JavaScript doesn't have any multithreading or multiprocessor capabilities.


Once again, JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.

JavaScript Development Tools

One of major strengths of JavaScript is that it does not require expensive development tools. You can
start with a simple text editor such as Notepad. Since it is an interpreted language inside the context
of a web browser, you don't even need to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Some
of them are listed here:

• Microsoft FrontPage: Microsoft has developed a popular HTML editor called


FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist
in the creation of interactive websites.

• Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very


popular HTML and JavaScript editor in the professional web development crowd.

• Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript editor from


Macromedia that can be used to manage personal websites effectively.

Syntax

JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.

Page 32 of 76
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it
is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a
script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:

• Language: This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.

• Type: This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".

So your JavaScript syntax will look as follows.

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Code

Let us take a sample example to print out "Hello World". We added an optional HTML comment that
surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//->". Here "//" signifies a comment in JavaScript, so we add
that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Next, we call a function document.write which writes a string into our HTML document.

Your First JavaScript Code

Let us take a sample example to print out "Hello World". We added an optional HTML comment that
surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//->". Here "//" signifies a comment in JavaScript, so we add
that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Next, we call a function document.write which writes a string into our HTML document.

Page 33 of 76
This function can be used to write text, HTML, or both. Take a look at the following code.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body> </html>

This code will produce the following result:

Hello World!

Whitespace and Line Breaks

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces,
tabs, and newlines freely in your program and you are free to format and indent your programs in a
neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C,
C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are
placed on a separate line. For example, the following code could be written without semicolons.
<script language="javascript" type="text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, you must use semicolons:

Page 34 of 76
<script language="javascript" type="text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity

JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.

So the identifiers Time and TIME will convey different meanings in JavaScript.

NOTE: Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript

JavaScript supports both C-style and C++-style comments. Thus:

• Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.

• Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.

• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as
a single-line comment, just as it does the // comment.

• The HTML comment closing sequence --> is not recognized by JavaScript so it should be written
as //-->.

Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--

// This is a comment. It is similar to comments in C++

Page 35 of 76
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an HTML file are as follows:

• Script in <head>...</head> section.

• Script in <body>...</body> section.

• Script in <body>...</body> and <head>...</head> sections.

• Script in an external file and then include in <head>...</head> section.


In the following section, we will see how we can place JavaScript in an HTML file in different ways.

JavaScript in <head>...</head> Section

If you want to have a script run on some event, such as when a user clicks somewhere, then you will
place that script in the head as follows.

Page 36 of 76
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body> </html>

This code will produce the following results:

Click here for the result


Say Hello

JavaScript in <body>...</body> Section

If you need a script to run as the page loads so that the script generates content in the page, then the
script goes in the <body> portion of the document. In this case, you would not have any function
defined using JavaScript. Take a look at the following code.

Page 37 of 76
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body> </html>

This code will produce the following results:

Hello World
This is web page body

JavaScript in <body> and <head> Sections

You can put your JavaScript code in <head> and <body> section altogether as follows.

<html>
<head>
<script type="text/javascript">

<!--
function sayHello() { alert("Hello
World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--

Page 38 of 76
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body> </html>

This code will produce the following result.


HelloWorld
Say Hello

JavaScript in External File

As you begin to work more extensively with JavaScript, you will be likely to find that there are cases
where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides
a mechanism to allow you to store JavaScript in an external file and then include it into your HTML
files.

Here is an example to show how you can include an external JavaScript file in your HTML code using
script tag and its src attribute.

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head> <body>
....... </body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown above.

For example, you can keep the following content in filename.js file and then you can use
sayHello function in your HTML file after including the filename.js file.

function sayHello() { alert("Hello World")


}

Page 39 of 76
JavaScript Datatypes

One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.

JavaScript allows you to work with three primitive data types:

• Numbers, e.g., 123, 120.50 etc.

• Strings of text, e.g. "This text string" etc.

• Boolean, e.g. true or false.


JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object. We will cover objects in detail in a separate chapter.

Note: Java does not make a distinction between integer values and floatingpoint values. All
numbers in JavaScript are represented as floating-point values.

JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754
standard.

JavaScript Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. You can place data into these containers and then refer to the data simply by
naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with
the var keyword as follows.
<script type="text/javascript">
<!-- var
money;
var name;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows:

<script type="text/javascript">
<!-- var money, name;

Page 40 of 76
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.

For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
<!--
var name =
"Ali"; var
money; money =
2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of any variable
name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data
type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what
type of value the variable will hold. The value type of a variable can change during the execution of a
program and JavaScript takes care of it automatically.

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables have
only two scopes.

• Global Variables: A global variable has global scope which means it can be defined
anywhere in your JavaScript code.

• Local Variables: A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.

Javascript

Within the body of a function, a local variable takes precedence over a global variable with the same
name. If you declare a local variable or function parameter with the same name as a global variable,
you effectively hide the global variable. Take a look into the following example.

Page 41 of 76
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);

}
//-->
</script>

It will produce the following result:

Local

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.

• You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.

• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but
_123test is a valid one.

• JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.

What is an Operator?

Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and
‘+’ is called the operator. JavaScript supports the following types of operators.

• Arithmetic Operators

• Comparison Operators

• Logical (or Relational) Operators

Page 42 of 76
• Assignment Operators

• Conditional (or ternary) Operators


• Let’s have a look at all the operators one by one.

• Arithmetic Operators

• JavaScript supports the following arithmetic operators:
• Assume variable A holds 10 and variable B holds 20, then:
S. No. Operator and Description

1 + (Addition)
Adds two operands

Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first

Ex: A - B will give -10

3 * (Multiplication)
Multiply both operands

Ex: A * B will give 200

4 / (Division)

Divide the numerator by the denominator

Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division

Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one

Ex: A++ will give 11

Page 43 of 76
Input and Output Statements

In order for a computer program to perform any useful work, it must be able to
communicate with the outside world. The process of communicating with the
outside world is known as input/output or I/O. JavaScript includes two output
statements for displaying information on the computer’s screen, and two input
statements – one for reading in text input, the other for reading in numeric input.
Most imperative languages include mechanisms for performing other kinds of I/O
such as detecting where the mouse is pointing and accessing the contents of a disk
drive.

The three output statements included in JavaScript are document. write,


document. writeln and alert. These statements are of the general form:

 document.write(expression);
 document.writeln(expression);
 alert(expression)

where an “expression” can be a constant, a variable, a function call, or a collection


of these things connected by appropriate operators. Both the document.write and
document.writeln statements display the value of an expression on the computer
screen. The only difference between the two is that document.writeln starts a new
line after printing the value on the screen. For this reason, document.writeln is
pronounced as if it were written “document write line”.

Figure 8.4 contains a simple Watson JavaScript program together with the output
produced by the program.

 Program definition:

 <html>
 <body>

Page 44 of 76
 <pre>
 <script type="text/javascript">
o document.writeln("Hello World!");
 </script>
 </pre>
 </body>
 </html>

 Program output:

 Hello World!

Figure 8.4: A Watson JavaScript program and its output

This program consists of a single instruction:

document.writeln(“Hello World!”);

Since the expression contained in this document.writeln statement is the text


constant “Hello World!”, the program displays the value of that constant on a line
by itself, producing the output:

Hello World!

The program of Figure 8.5 illustrates the difference between document.write and
document.writeln. It also introduces numeric expressions and the concept of
sequence. The program consists of three output statements: two document.write
statements followed by a document.writeln. When run, it produces the following
line of output.

Page 45 of 76
There are 13 cookies in a baker’s dozen.

To understand how this program works we must first recall from our discussion
of the Watson Graphics Language that the statements of a program are executed
one after another in the order, or sequence, they appear. Hence, the first statement
to be executed is:

document.write(“There are ”);

This statement prints the following characters on computer’s display screen:

There are

While it is not apparent in the line shown above, if you look closely at the
statement, you will see that a space, or “blank” is supposed to follow the word
“are”. Because this statement is a “write” and not a “writeln” a new line of output
was not begun after these characters were displayed. Thus, the next program
output will immediately follow the characters just printed, on the same line.

Program definition

// Main Program
document.write ( "There are " ) ;
document.write ( 12 + 1 ) ;
document.write ( " cookies in a baker's dozen." ) ;

The general format of the text input statement is:

variable = prompt(message,defaultValue);

Page 46 of 76
In this statement, variable will be replaced with an actual program variable that
has been declared to be of type “Text”. This variable will hold the data entered by
the user. The message field will be replaced by a text string that contains a brief
message designed to prompt the user to enter the appropriate value. The
defaultValue field is used to specify a default text string that will be assigned to
the variable in case the user fails to enter any data when prompted to do so.

Thus, the text input statement:

firstName = prompt("Please enter your first name.", "unknown");

will prompt the user to enter his or her first name by displaying an input dialog
box on the screen with the prompt “Please enter your first name.” next to the input
field. Whatever characters the user types in will be stored in the variable
firstName. If the user simply dismisses the input dialog without entering any
characters, firstName will be assigned the text string “unknown” in order to
indicate that the user’s first name is unknown.

The Watson JavaScript numeric input statement is similar. It has the form:

variable = parseFloat(prompt(message,defaultValue));

The most obvious difference between Watson JavaScript’s text input statement
and its numeric input statement is that the numeric input statements include the
phrase “parseFloat()”. This phrase insures that Watson JavaScript will supply a
numeric entry pad to the end user so that only numeric data can be entered. In
addition, this statement requires that variable be replaced with a program variable
declared to be of type “numeric”. Also, while the message will continue to be a
text string, the defaultValue must be a numeric constant – rather than a text
constant.

The numeric input statement

Page 47 of 76
age = parseFloat(prompt(“Enter your age.”,0));

will prompt the user to enter his or her age by displaying a numeric entry pad on
the screen with the prompt “Enter your age.” next to the input field. The number
entered by the user will be stored in the variable age. If the user fails to enter a
number, zero will be assigned to age as a default value.

Figure 8.6 illustrates the versatility of programs that make use of input statements.
The program asks a user to enter his or her name. Next, it stores the characters
entered by the user into a text variable called firstName. The program then prints
a greeting using the contents of firstName along with some additional text strings.

Looking at Figure 8.6 more closely, we see that the first thing this program does
is to declare a text variable called firstName. Next, a text input statement is
executed which will prompt the user to enter his or her name, and store the text
string entered by that user into the variable firstName. If the user dismisses the
input dialog without entering any text, the default value, an empty string “”, will
be stored in firstName.

// Variables
var firstName ; /*TEXT*/

// Main Program
firstName = prompt ( "Please enter your first name." , "" ) ;
document.write ( "Hello " ) ;
document.write ( firstName ) ;
document.writeln ( ". Nice to meet you." ) ;
// Variables
var firstNum ; /*NUMERIC*/
var secondNum ; /*NUMERIC*/

Page 48 of 76
// Main Program
firstNum = parseFloat ( prompt ( "Enter a number." , 0 ) ) ;
secondNum = parseFloat ( prompt ( "Enter another number." , 0 ) ) ;
document.write ( "Guess what? The sum of " ) ;
document.write ( firstNum ) ;
document.write ( " and " ) ;
document.write ( secondNum ) ;
document.write ( " is " ) ;
document.write ( firstNum + secondNum ) ;
document.writeln ( "." ) ;

Page 49 of 76
PHP
Introduction

The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers
to create dynamic content that interacts with databases. PHP is basically used for developing
web based software applications. This tutorial helps you to build your base with PHP.

Why to Learn PHP?

PHP started out as a small open source project that evolved as more and more people found
out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.

PHP is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning PHP:

PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites.

It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,


Sybase, Informix, and Microsoft SQL Server.

PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the
Unix side. The MySQL server, once started, executes even very complex queries with huge
result sets in record-setting time.

PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object architectures (COM and CORBA), making n-tier
development a possibility for the first time.

PHP is forgiving: PHP language tries to be as forgiving as possible.

PHP Syntax is C-Like.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

Page 50 of 76
Simplicity

Efficiency

Security

Flexibility

Familiarity

Hello World using PHP.

Just to give you a little excitement about PHP, I'm going to give you a small conventional PHP
Hello World program, You can try it using Demo link.

Live Demo
<html>

<head>
<title>Hello World</title>
</head>

<body>
<?php echo "Hello, World!";
?>
</body>

</html>
Applications of PHP
As mentioned before, PHP is one of the most widely used language over the web. I'm going to
list few of them here:

PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.

PHP can handle forms, i.e. gather data from files, save data to a file, through email you can
send data, return data to the user.

Page 51 of 76
You add, delete, modify elements within your database through PHP.

Access cookies variables and set cookies.

Using PHP, you can restrict users to access some pages of your website.

It can encrypt data.

This PHP tutorial is designed for PHP programmers who are completely unaware of PHP
concepts but they have basic understanding on computer programming.

Prerequisites

Before proceeding with this tutorial you should have at least basic understanding of computer
programming, Internet, Database, and MySQL etc is very helpful.

PHP started out as a small open source project that evolved as more and more people found
out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.

PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites.

It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,


Sybase, Informix, and Microsoft SQL Server.

PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the
Unix side. The MySQL server, once started, executes even very complex queries with huge
result sets in record-setting time.

PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object architectures (COM and CORBA), making n-tier
development a possibility for the first time.

PHP is forgiving: PHP language tries to be as forgiving as possible.

PHP Syntax is C-Like.

Common uses of PHP

PHP performs system functions, i.e. from files on a system it can create, open, read, write, and

Page 52 of 76
close them.

PHP can handle forms, i.e. gather data from files, save data to a file, through email you can
send data, return data to the user.

You add, delete, modify elements within your database through PHP.

Access cookies variables and set cookies.

Using PHP, you can restrict users to access some pages of your website.

It can encrypt data.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

Simplicity

Efficiency

Security

Flexibility

Familiarity

"Hello World" Script in PHP

To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.

As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this −

Live Demo

<html>

<head>

<title>Hello World</title>

Page 53 of 76
</head>

<body>

<?php echo "Hello, World!";?>

</body>

</html>

It will produce following result −

Hello, World!

If you examine the HTML output of the above example, you'll notice that the PHP code is not
present in the file sent from the server to your Web browser. All of the PHP present in the Web
page is processed and stripped from the page; the only thing returned to the client from the
Web server is pure HTML output.

All PHP code must be included inside one of the three special markup tags ATE are recognised
by the PHP Parser.

<?php PHP code goes here ?>

<? PHP code goes here ?>

<script language = "php"> PHP code goes here </script>

A most common tag is the <?php...?> and we will also use the same tag in our tutorial.

From the next chapter we will start with PHP Environment Setup on your machine and then
we will dig out almost all concepts related to PHP to make you comfortable with the PHP
language.

PHP - Environment Setup

Page 54 of 76
In order to develop and run PHP Web pages three vital components need to be installed on
your computer system.

Web Server − PHP will work with virtually all Web Server software, including Microsoft's
Internet Information Server (IIS) but then most often used is freely available Apache
Server.

DBMS − PHP will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL BDMS. Download MySQL free here

PHP Parser − In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser. This tutorial will guide you
how to install PHP parser on your computer.

PHP Server

The PHP Community Provides Some types of Software Server solution under The GNU
(General Public License).

These are the following:

1. WAMP Server
2. LAMP Server
3. MAMP Server
4. XAMPP Server

All these types of software automatic configure inside operating system after installation it
having PHP, MySQL, Apache and operating system base configuration file, it doesn't need to
configure manually.

Server Stands for

WAMP Microsoft window o/s, Apache Mysql PHP


LAMP Linux Operating System Apache Mysql PHP
MAMP Mac os Apache Mysql PHP
XAMPP x-os(cross operating system) Apache Mysql PHP Perl

Page 55 of 76
The main way to store information in the middle of a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

All variables in PHP are denoted with a leading dollar sign ($).

The value of a variable is the value of its most recent assignment.

Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.

Variables can, but do not need, to be declared before assignment.

Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.

Variables used before they are assigned have default values.

PHP does a good job of automatically converting types from one to another when
necessary.

PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables −

Integers − are whole numbers, without a decimal point, like 4195.

Doubles − are floating-point numbers, like 3.14159 or 49.1.

Booleans − have only two possible values either true or false.

NULL − is a special type that only has one value: NULL.

Strings − are sequences of characters, like 'PHP supports string operations.'

Arrays − are named and indexed collections of other values.

Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.

Resources − are special variables that hold references to resources external to PHP (such
as database connections).

The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the

Page 56 of 76
simple types cannot.

We will explain only simple data type in this chapters. Array and Objects will be explained
separately.

Integers

They are whole numbers, without a decimal point, like 4195. They are the simplest type
.they correspond to simple whole numbers, both positive and negative. Integers can be
assigned to variables, or they can be used in expressions, like so −

$int_var = 12345;

$another_int = -12345 + 12345;

Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and
hexadecimals have a leading 0x.

For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code −

Live Demo

<?php

$many = 2.2888800;

$many_2 = 2.2111200;

$few = $many + $many_2;

print("$many + $many_2 = $few <br>");

?>

It produces the following browser output −

Page 57 of 76
2.28888 + 2.21112 = 4.5

Boolean

They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so −

if (TRUE)

print("This will always print<br>");

else

print("This will never print<br>");

Interpreting other types as Booleans

Here are the rules for determine the "truth" of any value not already of the Boolean type

If the value is a number, it is false if exactly equal to zero and true otherwise.

If the value is a string, it is false if the string is empty (has zero characters) or is the string
"0", and is true otherwise.

Values of type NULL are always false.

If the value is an array, it is false if it contains no other values, and it is true otherwise. For
an object, containing a value means having a member variable that has been assigned a
value.

Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).

Don't use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used
in a Boolean context.

$true_num = 3 + 0.14159;

$true_str = "Tried and true"

Page 58 of 76
$true_array[49] = "An array element";

$false_array = array();

$false_null = NULL;

$false_num = 999 - 999;

$false_str = "";

NULL

NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −

$my_var = null;

A variable that has been assigned NULL has the following properties −

It evaluates to FALSE in a Boolean context.

It returns FALSE when tested with IsSet() function.

Strings

They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string

$string_1 = "This is a string in double quotes";

$string_2 = 'This is a somewhat longer, singly quoted string';

$string_39 = "This string has thirty-nine characters";

$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

Live Demo

Page 59 of 76
<?php

$variable = "name";

$literally = 'My $variable will not print!';

print($literally);

print "<br>";

$literally = "My $variable will print!";

print($literally);

?>

This will produce following result −

My $variable will not print!

My name will print

There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −

Certain character sequences beginning with backslash (\) are replaced with special
characters

Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

\n is replaced by the newline character

\r is replaced by the carriage-return character

\t is replaced by the tab character

\$ is replaced by the dollar sign itself ($)

Page 60 of 76
\" is replaced by a single double-quote (")

\\ is replaced by a single backslash (\)

Here Document

You can assign multiple lines to a single string variable using here document −

Live Demo

<?php

$channel =<<<_XML_

<channel>

<title>What's For Dinner</title>

<link>http://menu.example.com/ </link>

<description>Choose what to eat tonight.</description>

</channel>

_XML_;

echo <<<END

This uses the "here document" syntax to output multiple lines with variable

interpolation. Note that the here document terminator must appear on a line with

just a semicolon. no extra whitespace!

END;

print $channel;

Page 61 of 76
?>

This will produce following result −

This uses the "here document" syntax to output

multiple lines with variable interpolation. Note

that the here document terminator must appear on a

line with just a semicolon. no extra whitespace!

<channel>

<title>What's For Dinner<title>

<link>http://menu.example.com/<link>

<description>Choose what to eat tonight.</description>

Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it
is declared. PHP variables can be one of four scope types −

Local variables

Function parameters

Global variables

Static variables

Variable Naming

Rules for naming a variable is −

Variable names must begin with a letter or underscore character.

A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc

There is no size limit for variables.

Previous Page Print Page

Page 62 of 76
Next Page

Advertisements

PHP - Constants Types


A constant is a name or an identifier for a simple value. A constant value cannot change during
the execution of the script. By default, a constant is case-sensitive. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant,
you have to simply specifying its name. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It
is stored in a variable or returned by a function.
constant() example
<?php
define("MINSIZE", 50);

echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables are
There is no need to write a dollar sign ($) before a constant, where as in Variable one has to
write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the define()
function.
Constants may be defined and accessed anywhere without regard to variable scoping rules.
Once the Constants have been set, may not be redefined or undefined.
Valid and invalid constant names
// Valid constant names

Page 63 of 76
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
define("__THREE__", "third value");

// Invalid constant names


define("2TWO", "second thing");

PHP Magic constants


PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For example,
the value of __LINE__ depends on the line that it's used on in your script. These special constants
are case-insensitive and are as follows −
A few "magical" PHP constants are given below −
Sr.No
Name & Description
1
__LINE__
The current line number of the file.
2
__FILE__
The full path and filename of the file. If used inside an include,the name of the included file is
returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it
contained relative path under some circumstances.
3
__FUNCTION__
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as
it was declared (case-sensitive). In PHP 4 its value is always lowercased.
4
__CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was
declared (case-sensitive). In PHP 4 its value is always lowercased.
5
__METHOD__

Page 64 of 76
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared
(case-sensitive).

PHP - Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5
are called operands and + is called operator. PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/

Page 65 of 76
Divide numerator by de-numerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9
Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition
becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value of right operand, if yes then condition
becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of right operand, if yes then condition
becomes true.
(A < B) is true.

Page 66 of 76
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes
then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then
condition becomes true.
(A <= B) is true.
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Operator
Description
Example
and
Called Logical AND operator. If both the operands are true then condition becomes true.
(A and B) is true.
or
Called Logical OR Operator. If any of the two operands are non zero then condition becomes
true.
(A or B) is true.
&&
Called Logical AND operator. If both the operands are non zero then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands are non zero then condition becomes
true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true
then Logical NOT operator will make false.
!(A && B) is false.
Assignment Operators

Page 67 of 76
There are following assignment operators supported by PHP language −
Show Examples
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to
left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign
the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign
the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the
result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result
to left operand
C %= A is equivalent to C = C % A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the result
of the evaluation. The conditional operator has this syntax −
Show Examples
Operator

Page 68 of 76
Description
Example
?:
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
Operators Categories
All the operators we have discussed above can be categorised into following categories −
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.
The conditional operator (a ternary operator), which takes three operands and evaluates either
the second or third expression, depending on the evaluation of the first expression.
Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Unary
! ++ --
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Relational

Page 69 of 76
< <= > >=
Left to right
Equality
== !=
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %=
Right to left

Exercise 1 (10 marks)


1. Define each of the following
 Web site
 Web page
 Hyperlink
2. state any four programming languages used form web development giving the use of each
3. What types of software or programs are required for writing and displaying HTML
document, give examples in each case.
4. Give the structure of an HTML document
5. Define tag and give any five examples
6. Differentiate between pair tag sand single tags given at least examples in each case
7. Define tag’s attribute and give three examples

Exercise 2 (10 marks)


2. Define HTML5 and give four of its advantages?
1. Use the followings tags to design the structure of an HTML 5 document <header>,
<footer>, <main>, <nav>, <section>, <article> and <aside>

Page 70 of 76
3. What is w3c and what is its main function
4. Explain the term "responsive design" as used in web design
5. The terms "HTML5 family" and "Web development trifecta" are sometimes used to refer
to which combination of Web technologies?
6. Which element introduced in HTML5 saves mobile device resources by avoiding the use
of plug-ins to play MP4 files?
7. What is the primary benefit of the HTML5 <video> element?
8. Write short HTML5 codes for carrying out the following in a web page
E. Inserting an image
F. Linking two web pages or web sites
G. Writing with list
H. Insert a video file
I. Insert an audio file
J. Insert word file
K. Insert a pdf file

Page 71 of 76
Exercise 3 (10 marks)
1. What is the full meaning of CSS and what is it used for?
2. Prior to CSS, how was the presentation of web pages managed and what were the
consequences of that?
3. State four main advantages of CSS
4. Define style rule as used with CSS
5. State the three main elements that makes up a style rule, illustrating your answer with an
example
6. Explain The following three methods used of including CSS in an HTML document, given
examples
i. Inline styles
ii. Embedded styles
iii. External style sheets

Exercise 4 (10 marks)


A) Write an HTML program to display the table and the fieldset bellow

Exercise 5(20 marks)


B) Write an HTML program to display the form bellow

Page 72 of 76
C) Write JavaScript codes to apply the following restrictions on the form above before
submitting it
i. The area to input the name and the
email must be filled otherwise a message :
“you must enter the name ” or “you must
enter the password is ” is displayed
ii. The contact number must be filled
otherwise a message “ phone number
absent “ is displayed
iii. The password field should not be
empty and must be either “petrol or
computer”
iv. When the user click on the button
SUBMIT , all the requirements above are
verified and in case all criteria are made , the
form is submitted , a message: “ welcome
followed with the name” is displayed and the user is taken to a web page called
Home.html

Exercise 6:
1. Differentiate between a server and a client computer (1mark)
2. State the use of each of the following web programming language (2marks)
 HTML
 CSS
 PHP
 MYSQL

Page 73 of 76
3. State a least four differences between Static and dynamic web page? (2 marks)
4. State and briefly explain any four competitors of PHP and MYSQL (4 marks)
5. Explain what happen when an internet user requests for a page from a server in each of
the following case: 3marks
 Static web page
 Dynamic web page
6. The purpose of building a web application is to make it accessible to the whole world,
explain the purpose and process of deploying a web application built in a local area
network. (2 marks)
7. State and give the function of each of the three main applications needed to run a PHP
project? (3 marks)
8. Create a form (HTML+ CSS) to authenticate users (Login, Password) see figure 1 (4marks)
9. Creates a php file (process.php) to get the parameters from the form and display them.
(4 marks)
10. What are the two main functions by PHP to connect to MYSQL 1mark

AUTHENTIFICATION

Login :

Password:

Submit Cancel

Figure 1: login form

Exercise 7
Considering the following program

1. <?php
2. $link = mysqli_connect("localhost", "root", "", "demo");
3. if($link === false){
4. die("ERROR: Could not connect. " . mysqli_connect_error());
5. }
6. $sql = "SELECT * FROM persons";
7. if($result = mysqli_query($link, $sql)){
8. if(mysqli_num_rows($result) > 0){
9. echo "<table>";
10. echo "<tr>";

74 | P a g e
11. echo "<th>id</th>";
12. echo "<th>first_name</th>";
13. echo "<th>last_name</th>";
14. echo "<th>email</th>";
15. echo "</tr>";
16. while($row = mysqli_fetch_array($result)){
17. echo "<tr>";
18. echo "<td>" . $row['id'] . "</td>";
19. echo "<td>" . $row['first_name'] . "</td>";
20. echo "<td>" . $row['last_name'] . "</td>";
21. echo "<td>" . $row['email'] . "</td>";
22. echo "</tr>";
23. }
24. echo "</table>";
25. mysqli_free_result($result);
26. } else{
27. echo "No records matching your query were found.";
28. }
29. } else{
30. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
31. }
32. mysqli_close($link);
33. ?>
a) State any three variables used in the program and give their use 2marks
b) Give the procedure to save the program and access it from a web browser 2marks
c) Assuming that you have connected your computer to your friend own , give the procedure
to access the page generated by the program from your friend computer, given that the IP
address of your computer is 192.168.10.1 3marks
d) State use of the following function used in the program 3marks
i. mysqli_connect
ii. mysqli_query
iii. mysqli_free_result
e) What does the program do? 4 marks

Exercise 8
Write a PHP code for the following
a) Make a connection to a MySQL database, and log in with valid credentials. The
connection resource should be stored in a variable with an appropriate name.2marks
b) Create a database school if it does not exist. 1mark
c) Create a table student with the following fields: 2marks
◦ USERNAME VARCHAR (100)
◦ Matricule CHAR(40)

75 | P a g e
◦ PHONE VARCHAR(10)
insert any three records into the table student 2marks
e) Select all the fields from the table student 2marks

76 | P a g e

You might also like