0% found this document useful (0 votes)
25 views161 pages

BIT3105 INTERNET PROGRAMMING Notes Final

Uploaded by

Dominic Chuchu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views161 pages

BIT3105 INTERNET PROGRAMMING Notes Final

Uploaded by

Dominic Chuchu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 161

WEB PROGRAMMING AND ADMINISTRATION

COURSE OUTLINE

Purpose: To understand the fundamentals of programming for the internet in the business world.

Objectives: By the end of the course unit the learner will gain knowledge and skills in: -

 Designing and implementing static web content


 Dynamic web content in web servers -
 Defining the web control using various types of business information

Course Assessments: Continuous Assessment Tests 30%

End of semester examination 70%


Reference Books:

Evangelos P. Magturing (2002) Visual basic 6 BPB Duplications

Mark S et al (1996), Special Edition using internet HTML Que Publishing Co ltd

Alex H et all(2000),, Professional active server Wrox publishers programmer to programmer series

BIT 3105: INTERNET PROGRAMMING - TOPICS – Details

Week 1: Introduction

 Services provided by the internet


 Important components of the web
 Common internet protocols
0  Internet architecture
Week 2: Web servers

 Introduction to web Servers


 Common features of a web server
 Web Server Types
 Web Server Error Messages
 Web server Overload
 Web Server software
Week 3: Static Content: Advanced HTML

 Introduction to static webpage


 HTML Forms
 HTML Doctypes
6
 HTML head Elements
 HTML Entities
 HTML Uniform Resource Locators

Week 4: Static Content: Introduction to XML

 Introduction to XML
 XML Tree
 XML Syntax
 XML Elements
 XML Attributes
 XML Validation
 XML Validator
 XML CSS

Week 5: Dynamic Content: Introduction to DHTML

 Introduction to Dynamic web page


 Introduction to DHTML
 DHTML JavaScript
 DHTML HTML Document Object Model
 DHTML Events
 DHTML CSS

Week 6-8: Dynamic Content: Introduction to PHP 8th Aug

 Introduction to PHP
 PHP Syntax
 PHP Variables
 PHP Operators
 Conditional Statements
 PHP Loops
 PHP Functions
 PHP Forms and User Input
 PHP $_GET Function
 PHP $_POST Function
 The PHP $_REQUEST Function

Week 9-10: PHP Database

 MySQL Introduction
 MySQL Connect
 MySQL Create
 MySQL Insert
 MySQL Select
 MySQL Where
 MySQL Order By
7
 MySQL Update
 MySQL Delete

Week 11: Advanced PHP

 PHP Include
 PHP File
 PHP File Upload
 PHP Cookies
 PHP Sessions
 PHP E-mail

Week 12: Multimedia websites

 Multimedia formats - Sound Formats, Video Formats, and Windows Formats


 Playing Sounds and Playing Videos
 Multimedia object element

STATIC CONTENT - ADVANCED HTML

Static Websites
 With static web sites, requests for pages are handled by a web server delivering the
content of these HTML files, "as is".
 Their content don’t change often. A static web page (sometimes called a flat page) is a
web page that is delivered to the user exactly as stored.
 static web page displays the same information for all users, from all contexts, subject
to modern capabilities of a web server to negotiate content-type or language of the
document where such versions are available and the server is configured to do so.
 Static web pages are often HTML documents stored as files in the file system and made
available by the web server over HTTP.
Advantages of a static website:
 Quick to develop
 Cheap to develop
 Cheap to host
 Inherently publicly cacheable (i.e. a cached copy can be shown to anyone).
 No particular hosting requirements are necessary.
 Can be viewed directly by a web browser without needing a web server or application server, for
example directly from a CD-ROM or USB Drive.
Disadvantages of a static website
 Requires web development expertise to update site
 Site not as useful for the user since content can get stagnant
 Any personalization or interactivity has to run client-side (ie. in the browser), which is
restricting.
 Maintaining large numbers of static pages as files can be impractical without automated
tools.

HTML Doctypes
 A doctype declaration refers to the rules for the markup language, so that the
browsers render the content correctly.

 The <!DOCTYPE> declaration is not

an HTML tag; it is an instruction to the web browser about what version of HTML the
page is written in.
 In HTML 4.01, the <!DOCTYPE> declaration refers to a Document Type Declaration
(DTD), because HTML 4.01 was based on Standard Generalized Markup
Language(SGML).
 The DTD specifies the rules for the markup language, so that the browsers render the
content correctly.
 HTML5 is not based on SGML, and therefore does not require a reference to a DTD.
 Always add the <!DOCTYPE> declaration to your HTML documents, so that the
browser knows what type of document to expect.

Example,

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>

This is my index page

</body>

</html>
HTML Different Doctypes

Common DOCTYPE Declarations

1. HTML 5

<!DOCTYPE html>
2. HTML 4.01 Strict

 This DTD contains all HTML elements and attributes, but does NOT INCLUDE
presentational or deprecated elements (like font).
 Framesets are not allowed.

<!DOCTYPE HTML PUBLIC


"-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/
strict.dtd">
3. HTML 4.01 Transitional

 This DTD contains all HTML elements and attributes, INCLUDING presentational
and deprecated elements (like font).
 Framesets are not allowed.

<!DOCTYPE HTML
PUBLIC "-//W3C//DTD
HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/
html4/loose.dtd">
 HTML 4.01 Frameset

This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.

<!DOCTYPE HTML PUBLIC


"-//W3C//DTD HTML 4.01
Frameset//EN"
"http://www.w3.org/TR/html4/fr
ameset.dtd">
XHTML 1.0 Strict

 This DTD contains all HTML elements and attributes, but does NOT INCLUDE
presentational or deprecated elements (like font).
 Framesets are not allowed.
 The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC


"-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtml
1/DTD/xhtml1-strict.dtd">
4. XHTML 1.0 Transitional

 This DTD contains all HTML elements and attributes, INCLUDING presentational and
deprecated elements (like font).
 Framesets are not allowed.
 The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

5. XHTML 1.0 Frameset

 This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

HTML head Elements


The head element is a container for all the head elements.
Elements inside <head> can include scripts, instruct the browser where to find style sheets and
provide meta information.

<h1 style="font-size:60px;">Heading 1</h1>


<h2 style="font-size:30px;">Heading 1</h2>
<h6 style="font-size:10px;">Heading 1</h6>
The following tags can be added to the head section: <title>, <base>, <link>, <meta>, <script>, and
<style>.
1. The HTML title Element
Define a document title.
Required in every HTML and XHTML document.
The title element must not contain other elements, only text.
Only one title element is permitted in a document.
User agents may use the title in different ways.
For example:
 Web browsers usually display it in a window‟s title bar when the window is open, and (where
applicable) in the task bar when the window is minimized.
 It may become the default filename when saving the page.
 Search engines‟ web crawlers may pay particular attention to the words used in the title.
 provides a title for the page when it is added to favourites.
A simplified HTML document:

<html>
<head>
<title> My first page </title>
</head>
<body>
The content of the
document......
</body>
</html>

2. The HTML base Element


The <base> tag specifies a default address or a default target for all links on a page. Specifies a base
URL for all relative href and other links in the document. Must appear before any element that refers
to an external resource. HTML permits only one base element for each document. The base element
has attributes, but no contents.

<head>
<base href="http://www.mku.ac.ke" />
<base target="_blank" />
</head>
3. The HTML link Element
The <link> tag defines the relationship between a document and an external resource.
Specifies links to other documents, such as previous and next links, or alternate versions.
A common use is to link to external stylesheets, using the form:

<head>
<link rel="stylesheet" type="text/css"
href="url" title="description_of_style">
</head>

A document’s head element may contain any number of link elements. The link element has
attributes, but no contents.
4. The HTML style Element
The <style> tag is used to define style information for an HTML document. Inside the style element
you specify how HTML elements should render in a browser:

<head>
<style type="text/css">
body {background-color:yellow}
p {color:blue}
</style>
</head>

5. The HTML meta Element


 Metadata is information about data.
 The <meta> tag provides metadata about the HTML document.
 Metadata will not be displayed on the page, but will be machine parsable.
 Meta elements are typically used to specify page description, keywords, author of the
document, last modified, and other metadata.
 The <meta> tag always goes inside the head element.
 The metadata can be used by browsers (how to display content or reload page), search
engines (keywords), or other web services.
Keywords for Search Engines
 Some search engines will use the name and content attributes of the meta element to
index your pages.
 The following meta element defines a description of a page:

<meta name="description"
content="Free Web tutorials on HTML,
CSS, XML" />
 The following meta element defines keywords for a page:
<meta name="keywords" content="HTML, CSS, XML" />
 The intention of the name and content attributes is to describe the content of a page.

6. The HTML script Element

 The <script> tag is used to define a client-side script, such as a JavaScript.


 The script element either contains scripting statements or it points to an external script
file through the src attribute.
 The required type attribute specifies the MIME type of the script.
 Common uses for JavaScript are image manipulation, form validation, and dynamic
changes of content.
 The script below writes Hello World! to the HTML output:

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

7. The HTML noscript Element


 The<noscript>tag is used to provide an alternate content for users that have
disabled scripts in their browser or have a browser that doesn’t support client-side
scripting.
 The noscript element can contain all the elements that you can find inside the body
element of a normal HTML page.
 The content inside the noscript element will only be displayed if scripts are not
supported, or are disabled in the user’s browser:
HTML Entities
 Reserved characters in HTML must be replaced with character entities.
 Some characters are reserved in HTML eg use of < and >.
 It is not possible to use the less than (<) or greater than (>) signs in your text, because
the browser will mix them with tags.
 To actually display reserved characters, we must use character entities in the HTML
source code.
 A character entity looks like this:
&entity_name;
OR
&#entity_number;
 To display a less than sign we must write: &lt;to represent < or &#60; to represent >
 The advantage of using an entity name, instead of a number, is that the name is easier to
remember.
 The disadvantage is that browsers may not support all entity names (the support for
entity numbers is very good).

Non-breaking Space
 A common character entity used in HTML is the non-breaking space (&nbsp;).
 Browsers will always truncate spaces in HTML pages.
 If you write 10 spaces in your text, the browser will remove 9 of them, before displaying
the page.
 To add spaces to your text, you can use the &nbsp; character entity.

HTML Useful Character Entities


Note: Entity names are case sensitive!
Result Description Entity Name Entity Number
non-breaking space &nbsp; &#160;
< less than &lt; &#60;
> greater than &gt; &#62;
& Ampersand &amp; &#38;
¢ Cent &cent; &#162;
£ Pound &pound; &#163;
¥ Yen &yen; &#165;
€ Euro &euro; &#8364;
§ Section &sect; &#167;
© Copyright &copy; &#169;
® registered trademark &reg; &#174;
™ Trademark &trade; &#8482;

HTML Uniform Resource Locators


 A URL is another word for a web address.
 A URL can be composed of words, such as "w3schools.com", or an Internet Protocol
(IP) address: 192.68.20.50.
 Most people enter the name of the website when surfing, because names are easier to
remember than numbers.
 When you click on a link in an HTML page, an underlying <a>tag points to an address
on the world wide web.
 A Uniform Resource Locator (URL) is used to address a document (or other data) on the
world wide web.

Common URL Schemes


The table below lists some common schemes:
SchemeShort for.... Which pages will the scheme be used for...
http Hyper Text Transfer Protocol Common web pages starts with http://. Not
encrypted
https Secure HyperText Transfer Protocol
Secure web pages. All information exchanged
are encrypted
ftp File Transfer Protocol For downloading or uploading files to a
website. Useful for domain maintenance of a file
in your computer
HTML URL Encoding
 URL encoding converts characters into a format that can be transmitted over
the Internet.
 Web browsers request pages from web servers by using a URL. The URL is the address
of a web page, like: http://www.facebook.com.

HTML Forms
 HTML Forms are used to select different kinds of user input.
 HTML forms are used to pass data to a server.
 A form can contain input elements like text fields, checkboxes, radio-buttons, submit
buttons and more.
 A form can also contain select lists, textarea, fieldset, legend, and label elements.
 The <form> tag is used to create an HTML form:
<form>

input elements

</form>
The Input Element
The input element is used to select user information. An input element can vary in many ways,
depending on the type attribute. An input element can be of type text field, checkbox, password,
radio button, submit button, and more. The most used input types are described below.
1. Text Fields
<input type="text" /> defines a one-line input field that a user can enter text into:

EXAMPLE

<form>
First name: <input type="text" name="firstname"
/><br />
Last name: <input type="text" name="lastname" />
</form>
Note: The form itself is not visible.
Also note that the default width of a text field is 20 characters.

2. Password Field
<input type="password" /> defines a password field
The characters in a password field are masked (shown as asterisks or circles).

<form>

Password: <input type="password" name="pwd" />

</form>

3. Radio Buttons
<input type="radio" /> defines a radio button.
Radio buttons let a user select ONLY ONE one of a limited number of choices:

<form>

<input type="radio" name="sex" value="male" />


Male

<input type="radio" name="sex" value="female" />


Female
</form>

4. Checkboxes
<input type="checkbox" /> defines a checkbox.
Checkboxes let a user select ONE or MORE options of a limited number of choices.

<form>
<input type="checkbox" name="vehicle"
value="Bike" /> I have a bike <br />
<input type="checkbox" name="vehicle"
value="Car" /> I have a car
</form>
How the HTML code above looks in a browser:

I have a bike I have a car

5. Submit Button
<input type="submit" /> defines a submit button.
 A submit button is used to send form data to a server.
 The data is sent to the page specified in the form's action attribute.
 The file defined in the action attribute usually does something with the received input:

<form name="input" action="html_form_action.asp" method="get">

Username: <input type="text" name="user" />


<input type="submit" value="Submit" />
</form>

 If you type some characters in the text field above, and click the "Submit" button, the
browser will send your input to a page called "html_form_action.asp".
 The page will show you the received input.

HTML Form Tags


Tag Description
<form> Defines an HTML form for user input
<input /> Defines an input control
<textarea> Defines a multi-line text input control
<label> Defines a label for an input element
<fieldset> Defines a border around elements in a form
<legend> Defines a caption for a fieldset element
<select> Defines a select list (drop-down list)
<optgroup> Defines a group of related options in a select list
<option> Defines an option in a select list
<button> Defines a push button
JAVASCRIPT
 Is an object-based scripting language which is lightweight and cross-platform.
 Is not a compiled language, but it is a translated language.
 The JavaScript Translator (embedded in the browser) is responsible for translating
the JavaScript code for the web browser.
 Javascript example is easy to code.

<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for
learners");
</script>
</body>
</html>

 The script tag specifies that we are using JavaScript.


 The text/javascript is the content type that provides information to the browser
about the data.
 The document.write() function is used to display dynamic content through
JavaScript.

 JavaScript provides 3 places to put the JavaScript code:

1. Within body tag

<html>
<body>
<script type="text/javascript">
alert("Hello");
</script>
</body>
</html>
2. Within head tag

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello ");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

 Alert dialog box of JavaScript that is contained inside the head tag.
 In this example, we are creating a function msg().
 To create function in JavaScript, you need to write function with function_name as
given below.
 To call function, you need to work on event.

3. External JavaScript file ( .js file ).

 You can create external JavaScript file and embed it in many html page.
 It provides code reusability
 An external JavaScript file must be saved by .js extension.
 It is recommended to embed all JavaScript files into a single file. It increases the
speed of the webpage.

An external JavaScript file that prints Hello in a alert dialog box.

Save as message.js

function msg(){
alert("Hello ");
}
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.

Save as index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Application of JavaScript

 JavaScript is used to create interactive websites.


 It is mainly used for:

 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
 Displaying clocks etc
JavaScript Variable
 A JavaScript variable is simply a name of storage location.
 There are two types of variables in JavaScript :

 Local variable
 Global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>

1. JavaScript local variable


 Is declared inside block or function.
 It is accessible within the function or block only
<script>
function abc()
{
var x=10;//local variable
}
</script>
Or,

<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>

2. JavaScript global variable


 is accessible from any function.
 Are declared outside the function or declared with window object.

<html> function b(){


<body> document.writeln(data);
<script> }
var data=200;//global variable a();//calling JavaScript
function a(){ function
document.writeln(data); b();
} </script>
</body> </html>

Output

200 200

 It can also be declared outside the function or declared with window object.
 It can be accessed from any function.

<html> alert(value);
<body> }
<script>
var value=50;//global variable a();
function a(){ </script>
alert(value); </body>
} </html>
function b(){

Output
50

 declare JavaScript global variables inside function. You need to use window object.

Eg

window.value=90;

 Now it can be declared inside any function and can be accessed from any function.
 For example:

<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>

Output
100

Internals of global variable in JavaScript

 When you declare a variable outside the function, it is added in the window object
internally.
 You can access it through window object also.
 For example:

var value=50;
function a(){
alert(window.value);//accessing global variable
}
Data Types
 JavaScript provides different data types to hold different types of values.
 There are two types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

 JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here to
specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

var a=40;//holding number


var b="Rahul";//holding string
JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of same type)
10==20 = false
Not equal to 10!=20 = true
!== Not Identical 10!==20 = true
Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
Less than 20<10 = false
<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:

Operator Description Example


Bitwise AND (10==20 & 20==33) = false
Bitwise OR (10==20 | 20==33) = false
Bitwise XOR (10==20 ^ 20==33) = false
Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero
(10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator
Description Example
&& Logical AND
(10==20 && 20==33) = false
Logical OR(10==20 || 20==33) = false
Logical Not
!(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.


Operator Description Example
Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
Subtract and assign
var a=20; a-=10; Now a = 10
*= Multiply and assign
var a=10; a*=20; Now a = 200
Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign
var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
In Operator checks if object has the given property
instanceof
checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is given
below.
if(expression){

//content to be evaluated

Example

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement
is given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Example

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Example

<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just
like else if statement that we have learned in previous page. But it is convenient than if..else..if
because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

Example

<script> case 'A':


var grade='B'; result="A Grade";
var result; break;
switch(grade){ case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result)
;
</script>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops.
It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment/decrement)


{
code to be executed
}

Example

<script>
Var i;
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:

1
2
3
4
5

JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}

Example

<script>
var i=20;
while (i>=0)
{
document.write(i + "&nbsp&nbsp&nbsp ");
i=i-2;
}
</script>
Output:

11
12
13
14
15
JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. The syntax of do while loop is
given below.

do{
code to be executed
}while (condition);

Example

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:

21
22
23
24
25

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.
Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.

Function Syntax

The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}

JavaScript Functions can have 0 or more arguments.

Function Example

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Function Arguments

We can call function by passing arguments.

Example

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of function
that returns value.

<script>
function getInfo(){
return "hello javaweb! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javaweb! How r u?

JAVASCRIPT
 Is an object-based scripting language which is lightweight and cross-platform.
 Is not a compiled language, but it is a translated language.
 The JavaScript Translator (embedded in the browser) is responsible for translating
the JavaScript code for the web browser.
 Javascript example is easy to code.

<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for
learners");
</script>
</body>
</html>

 The script tag specifies that we are using JavaScript.


 The text/javascript is the content type that provides information to the browser
about the data.
 The document.write() function is used to display dynamic content through
JavaScript.

 JavaScript provides 3 places to put the JavaScript code:

4. Within body tag

<html>
<body>
<script type="text/javascript">
alert("Hello");
</script>
</body>
</html>
5. Within head tag

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello ");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

 Alert dialog box of JavaScript that is contained inside the head tag.
 In this example, we are creating a function msg().
 To create function in JavaScript, you need to write function with function_name as
given below.
 To call function, you need to work on event.

6. External JavaScript file ( .js file ).

 You can create external JavaScript file and embed it in many html page.
 It provides code reusability
 An external JavaScript file must be saved by .js extension.
 It is recommended to embed all JavaScript files into a single file. It increases the
speed of the webpage.

An external JavaScript file that prints Hello in a alert dialog box.

Save as message.js

function msg(){
alert("Hello ");
}
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.

Save as index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Application of JavaScript

 JavaScript is used to create interactive websites.


 It is mainly used for:

 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
 Displaying clocks etc

JavaScript Variable
 A JavaScript variable is simply a name of storage location.
 There are two types of variables in JavaScript :

 Local variable
 Global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

4. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


5. After first letter we can use digits (0 to 9), for example value1.
6. JavaScript variables are case sensitive, for example x and X are different variables.

<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>

3. JavaScript local variable


 Is declared inside block or function.
 It is accessible within the function or block only
<script>
function abc()
{
var x=10;//local variable
}
</script>

Or,

<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>

4. JavaScript global variable


 is accessible from any function.
 Are declared outside the function or declared with window object.
<html> document.writeln(data);
<body> }
<script> a();//calling JavaScript
var data=200;//global variable function
function a(){ b();
document.writeln(data); </script>
} </body>
function b(){ </html>

Output

200 200

 It can also be declared outside the function or declared with window object.
 It can be accessed from any function.

<html> alert(value);
<body> }
<script>
var value=50;//global variable a();
function a(){ </script>
alert(value); </body>
} </html>
function b(){

Output
50

 declare JavaScript global variables inside function. You need to use window object.

Eg

window.value=90;

 Now it can be declared inside any function and can be accessed from any function.
 For example:

<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>

Output
100

Internals of global variable in JavaScript

 When you declare a variable outside the function, it is added in the window object
internally.
 You can access it through window object also.
 For example:

var value=50;
function a(){
alert(window.value);//accessing global variable
}

Data Types
 JavaScript provides different data types to hold different types of values.
 There are two types of data types in JavaScript.

3. Primitive data type


4. Non-primitive (reference) data type

 JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here to
specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

var a=40;//holding number


var b="Rahul";//holding string
JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined
represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

2. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

7. Arithmetic Operators
8. Comparison (Relational) Operators
9. Bitwise Operators
10. Logical Operators
11. Assignment Operators
12. Special Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
Operator Description Example
Addition 10+20 = 30
Subtraction 20-10 = 10
Multiplication 10*20 = 200
Division 20/10 = 2
Modulus (Remainder)
20%10 = 0
++ Increment var a=10; a++; Now a = 11
Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of same type)
10==20 = false
Not equal to 10!=20 = true
!== Not Identical 10!==20 = true
Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
Less than 20<10 = false
<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:

Operator Description Example


Bitwise AND (10==20 & 20==33) = false
Bitwise OR (10==20 | 20==33) = false
Bitwise XOR (10==20 ^ 20==33) = false
Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero
(10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.


Operator
Description Example
&& Logical AND
(10==20 && 20==33) = false
Logical OR(10==20 || 20==33) = false
Logical Not
!(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example


Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
Subtract and assign
var a=20; a-=10; Now a = 10
*= Multiply and assign
var a=10; a*=20; Now a = 200
Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign
var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
In Operator checks if object has the given property
instanceof
checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.

4. If Statement
5. If else statement
6. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is given
below.

if(expression){

//content to be evaluated

Example

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement
is given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Example
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Example
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just
like else if statement that we have learned in previous page. But it is convenient than if..else..if
because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result)
;
</script>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops.
It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

5. for loop
6. while loop
7. do-while loop
8. for-in loop

JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment/decrement)


{
code to be executed
}

Example

<script>
Var i;
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:

1
2
3
4
5

JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}

Example

<script>
var i=20;
while (i>=0)
{
document.write(i + "&nbsp&nbsp&nbsp ");
i=i-2;
}
</script>
Output:

11
12
13
14
15
JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. The syntax of do while loop is
given below.

do{
code to be executed
}while (condition);

Example

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:

21
22
23
24
25

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.
Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

3. Code reusability: We can call a function several times so it save coding.


4. Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.

Function Syntax

The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}

JavaScript Functions can have 0 or more arguments.

Function Example

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Function Arguments

We can call function by passing arguments.

Example

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of function
that returns value.

<script>
function getInfo(){
return "hello javaweb! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javaweb! How r u?

eXtensible Markup Language (XML)

XML

 XML stands for eXtensible Markup Language.


 XML was designed to store and transport data.
 XML was designed to be both human- and machine-readable.
 XML is a markup language much like HTML.
 XML was designed to describe data.
 XML uses a DTD (Document Type Definition) to formally describe the data.

XML is Extensible
 The tags used to markup HTML documents and the structure of HTML documents are
predefined.
 The author of HTML documents can only use tags that are defined in the HTML
standard.
 XML tags are not predefined in XML. XML allows the author to define his own tags
and his own document structure.
 XML is self-describing.

XML is a complement to HTML


 It is important to understand that XML is not a replacement for HTML.
 In the future development of the Web it is most likely that XML will be used to
structure and describe the Web data, while HTML will be used to format and display
the same data

The main difference between XML and HTML


XML was designed to describe data and to focus on what data is. HTML was designed
to display data and to focus on how data looks.

How can XML be used?


 XML can keep data separated from your HTML
 XML can be used to store data inside HTML documents
 XML can be used as a format to exchange information
 XML can be used to store data in files or in databases

XML can keep data separated from your HTML

 HTML pages are used to display data.


 Data is often stored inside HTML pages.
 With XML this data can now be stored in a separate XML file.
 This way you can concentrate on using HTML for formatting and display, and be sure
that changes in the underlying data will not force changes to any of your HTML code.

XML can also store data inside HTML documents

 XML data can also be stored inside HTML pages as “Data Islands”.
 You can still concentrate on using HTML for formatting and displaying the data.

XML can be used to exchange data

 In the real world, computer systems and databases contain data in incompatible formats.
 One of the most time consuming challenges for developers has been to exchange data
between such systems over the Internet.
 Converting the data to XML can greatly reduce this complexity and create data that can
be read by different types of applications.

XML can be used to store data

 XML can also be used to store data in files or in databases.


 Applications can be written to store and retrieve information from the store, and generic
applications can be used to display the data.
XML Syntax
An example XML document:
<?xml version="1.0"?>
<note>
<to>Harriet</to>
<from>Joeph</from>
<heading>Reminder</heading>
<body>Don't forget to come for the class this weekend!</body>
</note>

the first line in the document:

<?xml version="1.0"?>

 The XML declaration should always be included.


 It defines the XML version of the document.
 In this case the document conforms to the 1.0 specification of XML

The second line

<note>

 defines the first element of the document (the root element):

The third to sixth lines

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget to come for the class this weekend!</body>

 defines 4 child elements of the root (to, from, heading, and


body)

The last line

</note>

 defines the end of the root element

XML tree

 XML documents have a hierarchical structure and can conceptually be interpreted as a


tree structure, called an XML tree.
 XML documents must contain a root element (one that is the parent of all other
elements).
 All elements in an XML document can contain sub elements, text and attributes.
 XML Tree plays an important role to describe any XML document easily.
 The tree structure contains root (parent) elements, child elements and so on.
 By using tree structure, you can get to know all succeeding branches and sub-branches
starting from the root.
 The parsing starts at the root, then moves down the first branch to an element, take the
first branch from there, and so on to the leaf nodes.

Example
<?xml version = "1.0"?>
<Company>
<Employee>
<FirstName>Harriet</FirstName>
<LastName>Tsinale</LastName>
<ContactNo>0729784534</ContactNo>
<Email>tharriet@yahoo.com</Email>
<Address>
<City>Nairobi</City>
<Town>Thika</Town>
<Zip>+254</Zip>
</Address>
</Employee>
</Company>

 Following tree structure represents the above XML document −

Company

Employee

FirstName LastName ContactNo Email Address

City Town Zip


In the above diagram, there is a root element named as <company>. Inside that, there is one more
element <Employee>. Inside the employee element, there are five branches named <FirstName>,
<LastName>, <ContactNo>, <Email>, and <Address>. Inside the <Address> element, there are
three sub-branches, named <City><State> and <Zip>.

xml elements
 In HTML some elements do not have to have a closing tag. Eg
<p>This is a paragraph

 In XML all elements must have a closing tag like this:

<p>This is a paragraph</p>

 XML tags are case sensitive. The tag <Letter> is different from the tag <letter>. Opening
and closing tags must therefore be written with the same case. Eg

<message>This is correct</message>

 All XML elements must be properly nested.


 In HTML some elements can be improperly nested within each other . eg
<b><i>This text is bold and italic</b></i>
 In XML all elements must be properly nested within each other like this
<b><i>This text is bold and italic</i></b>
 All XML documents must have a root tag
 All XML documents must contain a single tag pair to define the root element.
 All other elements must be nested within the root element.
 All elements can have sub (children) elements.
 Sub elements must be in pairs and correctly nested within their parent element
<root>
<child>
<subchild>
</subchild>
</child>
</root>
 Attribute values must always be quoted

 XML elements can have attributes in name/value pairs just like in HTML.
 In XML the attribute value must always be quoted eg date="12/11/99" in the
following example
<?xml version="1.0"?>
<note date="12/11/99">
<to>Harriet</to>
<from>Joeph</from>
<heading>Reminder</heading>
<body>Don't forget to come for the class this
weekend!</body>
</note>
 The syntax for writing comments in XML is similar to that of HTML.
<!-- This is a comment -->
Entity References

 Some characters have a special meaning in XML.


 If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.
 This will generate an XML error:

<message>if salary <1000 then</message>

 To avoid this error, replace the "<" character with an entity reference:

<message>if salary &lt; 1000 then</message>

There are 5 predefined entity references in XML:

&lt; <less than


&gt; >greater than
&amp; &Ampersand
&apos; 'Apostrophe
&quot; "quotation mark

XML elements must follow these naming rules:

 Names can contain letters, numbers, and other characters


 Names cannot start with a number or punctuation character
 Names cannot start with the letters xml (or XML, or Xml, etc)
 Names cannot contain spaces

Best Naming Practices

 Names with an underscore separator are nice: <first_name>, <last_name>.


 Names should be short and simple, like this: <book_title> not like this:
<the_title_of_the_book>.
 Avoid "-" characters. If you name something "first-name," some software may think you
want to subtract name from first.
 Avoid "." characters. If you name something "first.name," some software may think that
"name" is a property of the object "first."
 Avoid ":" characters. Colons are reserved to be used for namespaces
 XML documents often have a corresponding database. A good practice is to use the
naming rules of your database for the elements in the XML documents.
 Non-English letters like Kitabu are perfectly legal in XML, but watch out for problems if
your software vendor doesn't support them.

XML Attributes
 XML attributes are normally used to describe XML elements.
 They provide additional information about elements.
 From HTML you can remember this construct: <IMG SRC=”computer.gif”>. In this
HTML example SRC is an attribute to the IMG element. The SRC attribute provides
additional information about the element.
 Attributes are always contained within the start tag of an element.

examples:

HTML examples:

<img src="computer.gif">
<a href="demo.asp">

XML examples:

<file type="gif">
<person id="3344">

 Usually attributes are used to provide information that is not a part of the content of the
XML document.

Use of Elements vs. Attributes

Take a look at these examples:

Using an Attribute for gender:

<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

Using an Element for gender:

<person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>

</person>

 In the first example gender is an attribute.


 In the last example sex is an element.
 Both examples provides the same information to the reader.
 There are no fixed rules about when to use attributes to describe data, and when to use
elements.
 Attributes are handy in HTML, but in XML you should try to avoid them, as long as the
same information can be expressed using elements.
 another example, demonstrating how elements can be used instead of attributes.

The following three XML documents contain exactly the same information.

A date attribute is used in the first, a date element is used in the second, and an expanded date
element is used in the third:

1. <?xml version="1.0"?>
<note date="20/02/2018">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

2. <?xml version="1.0"?>
<note>
<date>20/02/2018</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

3. <?xml version="1.0"?>
<note>
<date>
<day>20</day>
<month>02</month>
<year>2018</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Avoid using attributes

problems using attributes:

 attributes cannot contain multiple values (elements can)


 attributes are not expandable (for future changes)
 attributes cannot describe structures (like child elements can)
 attributes are more difficult to manipulate by program code
 attribute values are not easy to test against a DTD

If you start using attributes as containers for XML data, you might end up with documents that are
both difficult to maintain and to manipulate.

XML Validation

 XML with correct syntax is "Well Formed" XML.


 XML validated against a DTD is "Valid" XML.
Well Formed XML Documents
 A "Well Formed" XML document has a correct XML syntax.

 Eg

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Valid XML Documents
 A "Valid" XML document is a "Well Formed" XML document, which also conforms to
the rules of aDocument Type Definition (DTD)
eg
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE note SYSTEM "Note.dtd">


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

 The DOCTYPE declaration in the example above, is a reference to an external DTD file.
 The content of the file is shown in the paragraph below.

Viewing XML Files


 Raw XML files can be viewed in all major browsers.
 Don't expect XML files to be displayed as HTML pages.

<?xml version="1.0" encoding="ISO-8859-1"?>


- <note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
- The XML document will be displayed with colour-coded root and child elements.
- A plus (+) or minus sign (-) to the left of the elements can be clicked to expand or collapse
the element structure.
- To view the raw XML source (without the + and - signs), select "View Page Source" or
"View Source" from the browser menu.

Displaying XML Files with CSS?


The following example show how to use CSS to format an XML document.

The second line links the XML file to the CSS file:

<?xml version="1.0" encoding="UTF-8"?>


<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
</CATALOG>

INTRODUCTION TO PHP
What is PHP?

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use
 HP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free.
 PHP is easy to learn and runs efficiently on the server side
 PHP can encrypt data

Basic PHP Syntax


 A PHP script can be placed anywhere in the document.
 A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

 The default file extension for PHP files is ".php".


 A PHP file normally contains HTML tags, and some PHP scripting code.
 Below, we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page:

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo"Hello World!";
?>
</body>
</html>

Comments in PHP

 A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
 Comments can be used to Let others understand what you are doing
 PHP supports several ways of commenting eg

<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5/* + 15 */ + 5;
echo $x;
?>

</body>
</html>

PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are NOT case-sensitive.

In the example below, all three echo statements below are legal (and equal):

<!DOCTYPE html>
<html>
<body>
<?php
ECHO"Hello World!<br>";
echo"Hello World!<br>";
EcHo"Hello World!<br>";
?>
</body>
</html>
Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
 After the execution of the statements above, the variable $txt will hold the value Hello
world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.

Note:

 When you assign a text value to a variable, put quotes around the value.
 Unlike other programming languages, PHP has no command for declaring a variable.
It is created the moment you first assign a value to it.
 Think of variables as containers for storing data.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)

Output Variables

The PHP echo statement is often used to output data to the screen.

 The following example will show how to output text and a variable:

<?php
$txt = "facebook.com";
echo"I love $txt!";
?>
 The following example will output the sum of two variables:

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP echo and print Statements
 echo and print are more or less the same.
 They are both used to output data to the screen.
 The differences are small:
 echo has no return value while print has a return value of 1 so it can be used
in expressions.
 echo can take multiple parameters (although such usage is rare) while print
can take one argument.
 echo is marginally faster than print.

The PHP echo Statement


 The echo statement can be used with or without parentheses: echo or echo().

Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):
Example
<?php
echo"<h2>PHP is Fun!</h2>";
echo"Hello world!<br>";
echo"I'm about to learn PHP!<br>";
echo"This ", "string ", "was ", "made ", "with multiple parameters.";
?>
Display Variables
The following example shows how to output text and variables with the echo statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "facebook.com";
$x = 5;
$y = 4;
echo"<h2>" . $txt1 . "</h2>";
echo"Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>

PHP Data Types


Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
PHP String

A string is a sequence of characters, eg "Hello world!".


A string can be any text inside quotes.
You can use single or double quotes:

<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo"<br>";
echo $y;
?>
PHP Integer

Rules for integers:


 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
In the following example $x is an integer.

The PHP var_dump() function returns the data type and value:
Example

<?php
$x = 5985;
var_dump($x);
?>

Output

int(5985)
PHP Float
A float (floating point number) is a number with a decimal point
In the following example $x is a float.
The PHP var_dump() function returns the data type and value:

Example

<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;
Booleans are often used in conditional testing.

PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array.
The PHP var_dump() function returns the data type and value:

Example

<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

Constants
 Constants are like variables except that once they are defined they
cannot be changed or undefined.

 A constant is an identifier (name) for a simple value. T

 The value cannot be changed during the script.

 A valid constant name starts with a letter or underscore (no $ sign


before the constant name).

 Unlike variables, constants are automatically global across the entire


script.

Create a PHP Constant

 To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)


Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false

The example below creates a constant with a case-sensitive name:


Example 1

<?php
define("GREETING", "Welcome to mku.ac.ke!");
echo GREETING;
?>
The example below creates a constant with a case-insensitive name:

Example2

<?php
define("GREETING", "Welcome to mku.ac.ke!", true);
echo greeting;
?>
Constants are Global

Constants are automatically global and can be used across the entire script.

The example below uses a constant inside a function, even if it is defined outside the function

Example
<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}

myTest();
?>
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You
can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


 The if statement executes some code if one condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}

 The example below will output "Have a good day!" if the current time (HOUR) is less
than 20:
Example
<?php
$t = date("H");
if ($t <"20")
{
echo"Have a good day!";
}
?>

PHP - The if...else Statement


 The if....else statement executes some code if a condition is true and another code if
that condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
} else
{
code to be executed if condition is false;
}
 The example below will output "Have a good day!" if the current time is less than 20, and
"Have a good night!" otherwise:
Example
<?php
$t = date("H");
if ($t <"20")
{
echo"Have a good day!";
}
else
{
echo"Have a good night!";
}
?>
PHP - The if...elseif....else Statement
 The if....elseif...else statement executes different codes for more than two
conditions.
Syntax
if (condition)
{
code to be executed if this condition is true;
}
elseif (condition)
{
code to be executed if this condition is true;
}
else
{
code to be executed if all conditions are false;
}
 The example below will output "Have a good morning!" if the current time is less than
10, and "Have a good day!" if the current time is less than 20. Otherwise it will output
"Have a good night!":
<?php
$t = date("H");

if ($t <"10")
{
echo"Have a good morning!";
}
elseif ($t <"20")
{
echo"Have a good day!";
} else
{
echo"Have a good night!";
}
?>
PHP - The switch Statement
se the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works:
 First we have a single expression n (most often a variable), that is evaluated once.
 The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed.
 Use break to prevent the code from running into the next case automatically.
 The default statement is used if no match is found.

Example
<?php
$favcolor = "green";

switch ($favcolor){
case"red":
echo"Your favorite color is red!";
break;
case"blue":
echo"Your favorite color is blue!";
break;
case"green":
echo"Your favorite color is green!";
break;
default:
echo"Your favorite color is neither red, blue, nor green!";
}
?>
Example 2
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>

PHP Loops
In PHP, we have the following looping statements:
 while- loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for- loops through a block of code a specified number of times

The PHP while Loop


 The while loop executes a block of code as long as the specified condition is true.
Syntax
Variable initialization
while (condition)
{
//code to be executed;
//increment or decrement;
}
 The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1
each time the loop runs ($x++):

Example
<?php
$x = 1;
while($x <= 5)
{
echo"The number is: $x <br>";
$x++;
}
?>
Example 2

<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>

1PHP Ne0sted While Loop


<?php
$i=1;
while($i<=3)
{
$j=1;
while($j<=3)
{
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>

Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
//code to be executed;
} while (condition);
 The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will
write some output, and then increment the variable $x with 1. Then the condition is
checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is
less than, or equal to 5:
Example

<?php
$x = 1;

do {
echo"The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

Example 2

<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>

 Notice that in a do while loop the condition is tested AFTER executing the statements
within the loop.
 This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
 The example below sets the $x variable to 6, then it runs the loop, and then the
condition is checked:
<?php
$x = 6;

do {
echo"The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

The PHP for Loop


 The for loop is used when you know in advance how many times the script should run.
Syntax

for (init counter; test counter; increment counter) {


code to be executed;
}
Parameters:
 init counter: Initialize the loop counter value
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
Example

<?php
for ($x = 0; $x <= 10; $x++){
echo"The number is: $x <br>";
}
?>

PHP Nested For Loop

<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop


PHP for each loop is used to traverse array elements.

Syntax
foreach( $array as $var ){
//code to be executed
}
?>

Example

<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>

Output:

Season is: summer


Season is: winter
Season is: spring
Season is: autumn
PHP Functions
PHP function is a piece of code that can be reused many times.

It can take input as argument list and return value.

There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions


We can declare and call user-defined functions easily.

Syntax
function functionname()
{
//code to be executed
}

Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be
start with numbers or special symbols.

PHP Functions Example


File: function1.php

<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>

Output:

Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:

Hello Sonoo
Hello Vimal
Hello John

Let's see the example to pass two argument in PHP function.

File: functionarg2.php

<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>

Output:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But we
can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need
to use ampersand (&) symbol before the argument name.

Let's see a simple example of call by reference in PHP.


File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

Hello Call By Reference

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.

File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>

Output:

Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


Let's see an example of PHP function that returns value.

File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>

Output:

Cube of 3 is: 27

PHP Form Handling


 We can create and use forms in PHP.
 To get form data, we need to use PHP superglobals $_GET and $_POST.
 The form request may be get or post.
 To retrieve data from get request, we need to use $_GET, for post request
$_POST.

PHP Get Form


 Get request is the default form request.
 The data passed through get request is visible on the URL browser so it is not
secured.
 You can send limited amount of data through get request.

Example to receive data from get request in PHP.

File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>

PHP Post Form


Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You
can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>

File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable
echo "Welcome: $name, your password is: $password";
?>

Output:
PHP Include File
PHP allows you to include file so that a page content can be reused many times. There are
two ways to include file in PHP.

1. include
2. require

Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or
PHP script in many PHP scripts.

PHP include example


PHP include is used to include file on the basis of given path. You may use relative or
absolute path of the file. Let's see a simple PHP include example.
File: menu.html
1. <a href="http://www.facebook.com">Facebook</a> |
2. <a href="http://www.contact.com/php-tutorial">PHP</a> |
3. <a href="http://www.javaweb.com/java-tutorial">Java</a> |
4. <a href="http://www.javaweb.com/html-tutorial">HTML</a>
File: include1.php
1. <?php include("menu.html"); ?>
2. <h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page

PHP require example


PHP require is similar to include. Let's see a simple PHP require example.

File: menu.html
1. <a href="http://www.javaweb.com">Home</a> |
2. <a href="http://www.javaweb.com/php-tutorial">PHP</a> |
3. <a href="http://www.javaweb.com/java-tutorial">Java</a> |
4. <a href="http://www.javaweb.com/html-tutorial">HTML</a>
File: require1.php
1. <?php require("menu.html"); ?>
2. <h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page

PHP include vs PHP require


If file is missing or inclusion fails, include allows the script to continue but require halts the
script producing a fatal E_COMPILE_ERROR level error.

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.

Syntax

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

1. setcookie("CookieName", "CookieValue");/* defining name and value only*/


2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 s
econds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example

1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>

Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.

File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>

INTRODUCTION TO MYSQL

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.

Databases are useful for storing information categorically. A company may have a database with the
following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL Database System

 PHP combined with MySQL are cross-platform

PHP MySQL Connect

Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to


use one of the 2 alternatives.

o mysqli_connect()
o PDO::__construct()

PHP mysqli_connect()

 PHP mysqli_connect() function is used to connect with MySQL database.


 It returns resource if connection is established or null.

Syntax

resource mysqli_connect (server, username, password)

EG

$conn = new mysqli($servername, $username, $password);


PHP mysqli_close()

 PHP mysqli_close() function is used to disconnect with MySQL database.


 It returns true if connection is closed or false.

 The connection will be closed automatically when the script ends.

Syntax
bool mysqli_close(resource $resource_link)

Open a Connection to MySQL


 Before we can access data in the MySQL database, we need to be able to connect to
the server:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo"Connected successfully";
?>

Database Queries

 A query is a question or a request.


 We can query a database for specific information and have a recordset returned.

SELECT LastName FROM Employees

 The query above selects all the data in the "LastName" column from the "Employees"
table.
PHP Create a MySQL Database

 A database consists of one or more tables.


 You will need special CREATE privileges to create or to delete a MySQL database.

<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo"Database created successfully";
} else {
echo"Error creating database: " . $conn->error;
}

$conn->close();
?>

 When you create a new database, you must only specify the first three arguments to the
mysqli object (servername, username and password).
 If you have to use a specific port, add an empty string for the database-name argument,
like this: new mysqli("localhost", "username", "password", "", port)

PHP Create MySQL Tables

 The CREATE TABLE statement is used to create a table in MySQL.


 We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo"Table MyGuests created successfully";
} else {
echo"Error creating table: " . $conn->error;
}
$conn->close();
?>

</body>
</html>
Another example

<html>
<body>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "create table Employee(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,primary key (id))";
if(mysqli_query($conn, $sql)){
echo "Table emp5 created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}

$conn->close();
?>

</body>
</html>
PHP Insert Data Into MySQL
The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

<html>
<body>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('Harriet', 'Tsinale', 'harriet@yahoo.com')";

if ($conn->query($sql) === TRUE) {


echo"New record created successfully";
} else {
echo"Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

</body>
</html>

Another example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';

$conn = mysqli_connect($host, $user, $pass,$dbname);


if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';


if(mysqli_query($conn, $sql)){
echo "Record inserted successfully";
}else{
echo "Could not insert record: ". mysqli_error($conn);
}

mysqli_close($conn);
?>

PHP Select Data From MySQL


Select Data From a MySQL Database

 The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

 or we can use the * character to select ALL columns from a table:


SELECT * FROM table_name

PHP code that is used to select data from MySQL

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows >0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo"0 results";
}
$conn->close();
?>

PHP Delete Data From MySQL

Delete Data From a MySQL Table Using MySQLi and PDO

 The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value
 Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies
which record or records that should be deleted. If you omit the WHERE clause, all
records will be deleted!
 id
firstname
lastname email reg_date
John Doe john@example.com2014-10-22 14:26:15
Mary Moe mary@example.com
2014-10-23 10:22:30
Julie Dooley julie@example.com2014-10-26 10:48:23

The following examples delete the record with id=3 in the "MyGuests" table:

Example of a php code that will be used to delete the record with id=3

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo"Record deleted successfully";
} else {
echo"Error deleting record: " . $conn->error;
}

$conn->close();
?>
PHP Update Data in MySQL
Update Data In a MySQL Table

 The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

 Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies
which record or records that should be updated.
 If you omit the WHERE clause, all records will be updated!

idfirstname
lastname email reg_date
John Doe john@example.com2014-10-22 14:26:15
Mary Moe mary@example.com
2014-10-23 10:22:30

The following examples update the record with id=2 in the "MyGuests" table:

Example of a php code that update the recode with id=2


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo"Record updated successfully";
} else {
echo"Error updating record: " . $conn->error;
}

$conn->close();
?>

HTML Multimedia
Multimedia on the web is sound, music, videos, movies, and animations.

What is Multimedia?

 Multimedia comes in many different formats. It can be almost anything you can hear or
see.
 Examples: Images, music, sound, videos, records, films, animations, and more.

Browser Support

 The first web browsers had support for text only, limited to a single font in a single color.
 Later came browsers with support for colors and fonts, and images!
 Audio, video, and animation have been handled differently by the major browsers.
Different formats have been supported, and some formats require extra helper programs
(plug-ins) to work.

Multimedia Formats

 Multimedia elements (like audio or video) are stored in media files.


 The most common way to discover the type of a file, is to look at the file extension.
 Multimedia files have formats and different extensions
like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Common Video Formats


MP4 is the new and upcoming format for internet video.

MP4 is recommended by YouTube.

MP4 is supported by Flash Players.

MP4 is supported by HTML5.

Format File Description


MPEG. Developed by the Moving Pictures Expert Group. The first popular video format on
.mpg
MPEG the web. Used to be supported by all browsers, but it is not supported in HTML5 (See
.mpeg
MP4).
AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras
AVI .avi
and TV hardware. Plays well on Windows computers, but not in web browsers.
WMV (Windows Media Video). Developed by Microsoft. Commonly used in video cameras
WMV .wmv
and TV hardware. Plays well on Windows computers, but not in web browsers.
QuickTime. Developed by Apple. Commonly used in video cameras and TV hardware. Plays
QuickTime
.mov
well on Apple computers, but not in web browsers. (See MP4)
.rm RealVideo. Developed by Real Media to allow video streaming with low bandwidths. It is
RealVideo
.ram still used for online video and Internet TV, but does not play in web browsers.
.swf Flash. Developed by Macromedia. Often requires an extra component (plug-in) to play in
Flash
.flv web browsers.
Ogg .ogg Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
WebM. Developed by the web giants, Mozilla, Opera, Adobe, and Google. Supported by
WebM .webm
HTML5.
MP4. Developed by the Moving Pictures Expert Group. Based on QuickTime. Commonly
MPEG-4
.mp4 used in newer video cameras and TV hardware. Supported by all HTML5 browsers.
or MP4
Recommended by YouTube.

MORE PHP Examples


Example 1

Table of Number
A table of a number can be printed using a loop in program.

Logic:

o Define the number.


o Run for loop.
o Multiply the number with for loop output.

Example:

We'll print the table of 7.

<?php
define('a', 7);
for($i=1; $i<=10; $i++)
{
echo $i*a;
echo '<br>';
}
?>
Output:
Sum of Digits
To find sum of digits of a number just add all the digits.

For example,

1. 14597 = 1 + 4 + 5 + 9 + 7
2. 14597 = 26

Logic:

o Take the number.


o Divide the number by 10.
o Add the remainder to a variable.
o Repeat the process until remainder is 0.

Example:

Given program shows the sum of digits of 14597.

<?php
$num = 14597;
$sum=0; $rem=0;
for ($i =0; $i<=strlen($num);$i++)
{
$rem=$num%10;
$sum = $sum + $rem;
$num=$num/10;
}
echo "Sum of digits 14597 is $sum";
?>

Output:

Even Odd Program


Even numbers are those which are divisible by 2. Numbers like 2,4,6,8,10, etc are even.

Odd numbers are those which are not divisible by 2. Numbers Like 1, 3, 5, 7, 9, 11, etc are odd.

Logic:

o Take a number.
o Divide it by 2.
o If the remainder is 0, print number is even.

Even Odd Program in PHP


A program to check 1233456 is odd or even is shown.

Example:

<?php
$number=1233456;
if($number%2==0)
{
echo "$number is Even Number";
}
else
{
echo "$number is Odd Number";
}
?>

Output:

Even Odd Program using Form in PHP


By inserting value in a form we can check that inserted value is even or odd.

Example:

<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
if($_POST){
$number = $_POST['number'];
//divide entered number by 2
//if the reminder is 0 then the number is even otherwise the number is odd
if(($number % 2) == 0){
echo "$number is an Even number";
}else{
echo "$number is Odd number";
}
}
?>

Output:

On entering the number 23456, following output appears.

On entering the number 285965, following output appears.

Prime Number
A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7, 11,
13, 17, etc. are prime numbers.

o 2 is the only even prime number.


o It is a natural number greater than 1 and so 0 and 1 are not prime numbers.
Prime number in PHP
Example:

Here is the Program to list the first 15 prime numbers.

1. <?php
2. $count = 0;
3. $num = 2;
4. while ($count < 15 )
5. {
6. $div_count=0;
7. for ( $i=1; $i<=$num; $i++)
8. {
9. if (($num%$i)==0)
10. {
11. $div_count++;
12. }
13. }
14. if ($div_count<3)
15. {
16. echo $num." , ";
17. $count=$count+1;
18. }
19. $num=$num+1;
20. }
21. ?>

Output:

Prime Number using Form in PHP


Example:
We'll show a form, which will check whether a number is prime or not.

1. <form method="post">
2. Enter a Number: <input type="text" name="input"><br><br>
3. <input type="submit" name="submit" value="Submit">
4. </form>
5. <?php
6. if($_POST)
7. {
8. $input=$_POST['input'];
9. for ($i = 2; $i <= $input-1; $i++) {
10. if ($input % $i == 0) {
11. $value= True;
12. }
13. }
14. if (isset($value) && $value) {
15. echo 'The Number '. $input . ' is not prime';
16. } else {
17. echo 'The Number '. $input . ' is prime';
18. }
19. }
20. ?>

Output:

On entering number 12, we get the following output. It states that 12 is not a prime number.

On entering number 97, we get the following output. It states that 97 is a prime number.
Factorial Program
The factorial of a number n is defined by the product of all the digits from 1 to n (including 1
and n).

For example,

1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720

Note:

o It is denoted by n! and is calculated only for positive integers.


o Factorial of 0 is always 1.

The simplest way to find the factorial of a number is by using a loop.

There are two ways to find factorial in PHP:

o Using loop
o Using recursive method

Logic:
o Take a number.
o Take the descending positive integers.
o Multiply them.
Factorial in PHP
Factorial of 4 using for loop is shown below.

Example:

1.<?php
2.$num = 4;
3.$factorial = 1;
4.for ($x=$num; $x>=1; $x--)
5.{
6. $factorial = $factorial * $x;
7.}
8.echo "Factorial of $num is $factorial";
9. ?>

Output:

Factorial using Form in PHP


Below program shows a form through which you can calculate factorial of any number.

Example:

<html>
<head>
<title>Factorial Program using loop in PHP</title>
</head>
<body>
<form method="post">
Enter the Number:<br>
<input type="number" name="number" id="number">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if($_POST){
$fact = 1;
//getting value from input text box 'number'
$number = $_POST['number'];
echo "Factorial of $number:<br><br>";
//start loop
for ($i = 1; $i <= $number; $i++){
$fact = $fact * $i;
}
echo $fact . "<br>";
}
?>
</body>
</html>

Output:

Factorial using Recursion in PHP


Factorial of 6 using recursion method is shown.

Example:
1. <?php
2. function fact ($n)
3. {
4. if($n <= 1)
5. {
6. return 1;
7. }
8. else
9. {
10. return $n * fact($n - 1);
11. }
12. }
13.
14. echo "Factorial of 6 is " .fact(6);
15. ?>

Output:

Armstrong Number
An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

0, 1, 153, 371, 407, 471, etc are Armstrong numbers.

For example,

1. 407 = (4*4*4) + (0*0*0) + (7*7*7)


2. = 64 + 0 + 343
3. 407 = 407

Logic:

o Take the number.


o Store it in a variable.
o Take a variable for sum.
o Divide the number with 10 until quotient is 0.
o Cube the remainder.
o Compare sum variable and number variable.

Armstrong number in PHP


Below program checks whether 407 is Armstrong or not.

Example:

1. <?php
2. $num=407;
3. $total=0;
4. $x=$num;
5. while($x!=0)
6. {
7. $rem=$x%10;
8. $total=$total+$rem*$rem*$rem;
9. $x=$x/10;
10. }
11. if($num==$total)
12. {
13. echo "Yes it is an Armstrong number";
14. }
15. else
16. {
17. echo "No it is not an armstrong number";
18. }
19. ?>

Output:
Look at the above snapshot, the output displays that 407 is an Armstrong number.

Armstrong number using Form in PHP


A number is Armstrong or can also be checked using a form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST)
12. {
13. //get the number entered
14. $number = $_POST['number'];
15. //store entered number in a variable
16. $a = $number;
17. $sum = 0;
18. //run loop till the quotient is 0
19. while( $a != 0 )
20. {
21. $rem = $a % 10; //find reminder
22. $sum = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum varia
ble till the loop ends
23. $a = $a / 10; //find quotient. if 0 then loop again
24. }
25. //if the entered number and $sum value matches then it is an armstrong number
26. if( $number == $sum )
27. {
28. echo "Yes $number an Armstrong Number";
29. }else
30. {
31. echo "$number is not an Armstrong Number";
32. }
33. }
34. ?>

Output:

On entering the number 371, we got the following output.

On entering the number 9999, we got the following output.

Palindrome Number
A palindrome number is a number which remains same when its digits are reversed.

For example, number 24142 is a palindrome number. On reversing it we?ll get the same
number.

Logic:

o Take a number.
o Reverse the input number.
o Compare the two numbers.
o If equal, it means number is palindrome
Palindrome Number in PHP
Example:

1. <?php
2. function palindrome($n){
3. $number = $n;
4. $sum = 0;
5. while(floor($number)) {
6. $rem = $number % 10;
7. $sum = $sum * 10 + $rem;
8. $number = $number/10;
9. }
10. return $sum;
11. }
12. $input = 1235321;
13. $num = palindrome($input);
14. if($input==$num){
15. echo "$input is a Palindrome number";
16. } else {
17. echo "$input is not a Palindrome";
18. }
19. ?>

Output:

Palindrome Number using Form in PHP


Example:

We'll show the logic to check whether a number is palindrome or not.


1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>

Output:

On entering the number 23432, we get the following output.

On entering the number 12345, we get the following output.


Fibonacci Series
Fibonacci series is the one in which you will get your next term by adding previous two
numbers.

For example,

1. 0 1 1 2 3 5 8 13 21 34
2. Here, 0 + 1 = 1
3. 1+1=2
4. 3+2=5

and so on.

Logic:
o Initializing first and second number as 0 and 1.
o Print first and second number.
o From next number, start your loop. So third number will be the sum of the first two
numbers.

Example:

We'll show an example to print the first 12 numbers of a Fibonacci series.

1. <?php
2. $num = 0;
3. $n1 = 0;
4. $n2 = 1;
5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";
6. echo "\n";
7. echo $n1.' '.$n2.' ';
8. while ($num < 10 )
9. {
10. $n3 = $n2 + $n1;
11. echo $n3.' ';
12. $n1 = $n2;
13. $n2 = $n3;
14. $num = $num + 1;
15. ?>

Output:

Fibonacci series using Recursive function


Recursion is a phenomenon in which the recursion function calls itself until the base condition is
reached.

1. <?php
2. /* Print fiboancci series upto 12 elements. */
3. $num = 12;
4. echo "<h3>Fibonacci series using recursive function:</h3>";
5. echo "\n";
6. /* Recursive function for fibonacci series. */
7. function series($num){
8. if($num == 0){
9. return 0;
10. }else if( $num == 1){
11. return 1;
12. } else {
13. return (series($num-1) + series($num-2));
14. }
15. }
16. /* Call Function. */
17. for ($i = 0; $i < $num; $i++){
18. echo series($i);
19. echo "\n";
20. }

Output:

Reverse number
A number can be written in reverse order.

For example

12345 = 54321

Logic:

o Declare a variable to store reverse number and initialize it with 0.


o Multiply the reverse number by 10, add the remainder which comes after dividing the
number by 10.

Reversing Number in PHP


Example:

Below progrem shows digits reversal of 23456.


1. <?php
2. $num = 23456;
3. $revnum = 0;
4. while ($num > 1)
5. {
6. $rem = $num % 10;
7. $revnum = ($revnum * 10) + $rem;
8. $num = ($num / 10);
9. }
10. echo "Reverse number of 23456 is: $revnum";
11. ?>

Output:

Reversing Number With strrev () in PHP


Example:

Function strrev() can also be used to reverse the digits of 23456.

1. <?php
2. function reverse($number)
3. {
4. /* writes number into string. */
5. $num = (string) $number;
6. /* Reverse the string. */
7. $revstr = strrev($num);
8. /* writes string into int. */
9. $reverse = (int) $revstr;
10. return $reverse;
11. }
12. echo reverse(23456);
13. ?>
Output:/strong>

Reverse String
A string can be reversed either using strrev() function or simple PHP code.

For example, on reversing JAVAWEB it will become TNIOPTAVAJ.

Logic:

o Assign the string to a variable.


o Calculate length of the string.
o Declare variable to hold reverse string.
o Run for loop.
o Concatenate string inside for loop.
o Display reversed string.

Reverse String using strrev() function


A reverse string program using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVAWEB";
3. echo "Reverse string of $string is " .strrev ( $string );
4. ?>

Output:
Reverse String Without using strrev() function
A reverse string program without using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVAWEB";
3. $length = strlen($string);
4. for ($i=($length-1) ; $i >= 0 ; $i--)
5. {
6. echo $string[$i];
7. }
8. ?>

Output:

Swapping two numbers


Two numbers can be swapped or interchanged. It means first number will become second and
second number will become first.

For example

1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20

There are two methods for swapping:

o By using third variable.


o Without using third variable.

Swapping Using Third Variable


Swap two numbers 45 and 78 using a third variable.

Example:

1. <?php
2. $a = 45;
3. $b = 78;
4. // Swapping Logic
5. $third = $a;
6. $a = $b;
7. $b = $third;
8. echo "After swapping:<br><br>";
9. echo "a =".$a." b=".$b;
10. ?>

Output:

Swapping Without using Third Variable


Swap two numbers without using a third variable is done in two ways:
o Using arithmetic operation + and ?
o Using arithmetic operation * and /

Example for (+ and -):

1. <?php
2. $a=234;
3. $b=345;
4. //using arithmetic operation
5. $a=$a+$b;
6. $b=$a-$b;
7. $a=$a-$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>

Output:

Example for (* and /):

<?php
$a=234;
$b=345;
// using arithmetic operation
$a=$a*$b;
$b=$a/$b;
$a=$a/$b;
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";
?>

Output:
Adding Two Numbers
There are three methods to add two numbers:

Adding in simple code in PHP

Adding in form in PHP

Adding without using arithmetic operator (+).

Adding in Simple Code


Addition of two numbers 15 and 30 is shown here.

Example:

<?php
$x=15;
$y=30;
$z=$x+$y;
echo "Sum: ",$z;
?>

Output:
Adding in Form
Two numbers can be added by passing input value in the form.

Example:

<html>
<body>
<form method="post">
Enter First Number:
<input type="number" name="number1" /><br><br>
Enter Second Number:
<input type="number" name="number2" /><br><br>
<input type="submit" name="submit" value="Add">
</form>
<?php
if(isset($_POST['submit']))
{
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$sum = $number1+$number2;
echo "The sum of $number1 and $number2 is: ".$sum;
}
?>
</body>
</html>

Output:
Adding in Simple Code
Two numbers can be added by passing input value in the form but without using (+) operator.

1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Add">
8. </form>
9. </body>
10. <?php
11. @$number1=$_GET['number1'];
12. @$number2=$_GET['number2'];
13. for ($i=1; $i<=$number2; $i++)
14. {
15. $number1++;
16. }
17. echo "Sum of $number1 and $number2 is=".$number2;
18. ?>

Output:
Subtracting Two Numbers
There are three methods to subtract two numbers:

o Subtraction in simple code in PHP


o Subtraction in form in PHP
o Subtraction without using arithmetic operator (+).

Subtraction in Simple Code


Subtraction of two numbers 30 and 15 is shown.

Example:

1. <?php
2. $x=30;
3. $y=15;
4. $z=$x-$y;
5. echo "Difference: ",$z;
6. ?>

Output:
Subtraction in Form
By inserting values in the form two numbers can be subtracted.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Subtract">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1-$number2;
16. echo "The difference of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>

Output:
Subtraction in Form without (-) Operator
By inserting values in the form two numbers can be subtracted but without using (-) operator.

Example:

1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Subtract">
8. </form>
9. </body>
10. <?php
11.
12. @$number1=$_GET['number1'];
13. @$number2=$_GET['number2'];
14. for ($i=1; $i<=$number2; $i++)
15. {
16. $number1--;
17. }
18. echo "Difference=".$number1;
19. ?>
Output:

Area of Triangle
Area of a triangle is calculated by the following Mathematical formula,

1. (base * height) / 2 = Area

Area of Triangle in PHP


Program to calculate area of triangle with base as 10 and height as 15 is shown.

Example:

1. <?php
2. $base = 10;
3. $height = 15;
4. echo "area with base $base and height $height= " . ($base * $height) / 2;
5. ?>

Output:
Area of Triangle with Form in PHP
Program to calculate area of triangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Base: <input type="number" name="base">
5. <br><br>
6. Height: <input type="number" name="height"><br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $base = $_POST['base'];
15. $height = $_POST['height'];
16. $area = ($base*$height) / 2;
17. echo "The area of a triangle with base as $base and height as $height is $area";
18. }
19. ?>

Output:
Area of a Rectangle
Area of a rectangle is calculated by the mathematical formula,

1. Length ∗ Breadth = Area

Logic:

o Take two variables.


o Multiply both of them.

Area of Rectangle in PHP


Program to calculate area of rectangle with length as 14 and width as 12 is shown.

Example:

1. <?php
2. $length = 14;
3. $width = 12;
4. echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
5. ?>

Output:
Area of Rectangle with Form in PHP
Program to calculate area of rectangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Width: <input type="number" name="width">
5. <br><br>
6. Length: <input type="number" name="length"> <br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $width = $_POST['width'];
15. $length = $_POST['length'];
16. $area = $width*$length;
17. echo "The area of a rectangle with $width x $length is $area";
18. }
19. ?>

Output:
Leap Year Program
A leap year is the one which has 366 days in a year. A leap year comes after every four years.
Hence a leap year is always a multiple of four.

For example, 2016, 2020, 2024, etc are leap years.

Leap Year Program


This program states whether a year is leap year or not from the specified range of years (1991 -
2016).

Example:

1. <?php
2. function isLeap($year)
3. {
4. return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);
5. }
6. //For testing
7. for($year=1991; $year<2016; $year++)
8. {
9. If (isLeap($year))
10. {
11. echo "$year : LEAP YEAR<br />\n";
12. }
13. else
14. {
15. echo "$year : Not leap year<br />\n";
16. }
17. }
18. ?>

Output:
Leap Year Program in Form
This program states whether a year is leap year or not by inserting a year in the form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Year: <input type="text" name="year">
5. <input type="submit" name="submit" value="Submit">
6. </form>
7. </body>
8. </html>
9. <?php
10. if($_POST)
11. {
12. //get the year
13. $year = $_POST['year'];
14. //check if entered value is a number
15. if(!is_numeric($year))
16. {
17. echo "Strings not allowed, Input should be a number";
18. return;
19. }
20. //multiple conditions to check the leap year
21. if( (0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400) )
22. {
23. echo "$year is a Leap Year";
24. }
25. else
26. {
27. echo "$year is not a Leap Year";
28. }
29. }
30. ?>

Output:

On entering year 2016, we get the following output.


On entering year 2019, we get the following output.

Alphabet Triangle Method


There are three methods to print the alphabets in a triangle or in a pyramid form.

o range() with for loop


o chr() with for loop
o range() with foreach loop

Logic:

o Two for loops are used.


o First for loop set conditions to print 1 to 5 rows.
o Second for loop set conditions in decreasing order.

Using range() function


This range function stores values in an array from A to Z. here, we use two for loops.

Example:

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Using chr() function


Here the chr() function returns the value of the ASCII code. The ASCII value of A, B, C, D, E is 65,
66, 67, 68, 69 respectively. Here, also we use two for loops.

Example:

1. <?php
2. for( $i=65; $i<=69; $i++){
3. for($j=5; $j>=$i-64; $j--){
4. echo chr($i);
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Alphabet Triangle Pattern
Some different alphabet triangle patterns using range() function in PHP are shown below.

Pattern 1

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 2

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 3

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 4

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=4; $j>=$i; $j--){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 5

1. <?php
2. $alpha = range('A', 'Z');
3. for ($i=5; $i>=1; $i--) {
4. for($j=0; $j<=$i; $j++) {
5. echo ' ';
6. }
7. $j--;
8. for ($k=0; $k<=(5-$j); $k++) {
9. echo $alpha[$k];
10. }
11. echo "<br>\n";
12. }
13. ?>

Output:
Number Triangle
Number triangle in PHP can be printed using for and foreach loop. There are a lot of patterns in
number triangle. Some of them are show here.

Pattern1

1. <?php
2. $k=1;
3. for($i=0;$i<4;$i++){
4. for($j=0;$j<=$i;$j++){
5. echo $k." ";
6. $k++;
7. }
8. echo "<br>";
9. }
10. ?>

Output:

Pattern 2

1. <?php
2. $k=1;
3. for($i=0;$i<5;$i++){
4. for($j=0;$j<=$i;$j++){
5. if($j%2==0)
6. {
7. $k=0;
8. }
9. else
10. {
11. $k=1;
12. }
13. echo $k." ";
14. }
15. echo "<br>";
16. }
17. ?>

Output:

Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Pattern 4

1. <?php
2. for($i=0;$i>=5;$i++){
3. for($j=1;$j>=$i;$j++){
4. echo $i;
5. }
6. echo "<br>";
7. }
8. ?<

Output:

Pattern 5

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>
Output:

Pattern 6

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 7

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>
Output:

Pattern 8

1. <?php
2. for($i=5;$i>=1;$i--){
3. for($j=$i;$j>=1;$j--){
4. echo $i." ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Star Triangle
The star triangle in PHP is made using for and foreach loop. There are a lot of star patterns.
We'll show some of them here.

Pattern 1

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 2

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($k=5;$k>=$i;$k--){
4. echo " ";
5. }
6. for($j=1;$j<=$i;$j++){
7. echo "* ";
8. }
9. echo "<br>";
10. }
11. for($i=4;$i>=1;$i--){
12. for($k=5;$k>=$i;$k--){
13. echo " ";
14. }
15. for($j=1;$j<=$i;$j++){
16. echo "* ";
17. }
18. echo "<br>";
19. }
20. ?>

Output:

Pattern 4

1. <?php
2. for($i=1; $i<=5; $i++){
3. for($j=1; $j<=$i; $j++){
4. echo ' * ';
5. }
6. echo '<br>';
7. }
8. for($i=5; $i>=1; $i--){
9. for($j=1; $j<=$i; $j++){
10. echo ' * ';
11. }
12. echo '<br>';
13. }
14. ?>

Output:

Pattern 5

1. <?php
2. for ($i=1; $i<=5; $i++)
3. {
4. for ($j=1; $j<=5; $j++)
5. {
6. echo '* ';
7. }
8. echo "</br>";
9. }
10. ?>

Output:
Pattern 6

1. <?php
2. for($i=5; $i>=1; $i--)
3. {
4. if($i%2 != 0)
5. {
6. for($j=5; $j>=$i; $j--)
7. {
8. echo "* ";
9. }
10. echo "<br>";
11. }
12. }
13. for($i=2; $i<=5; $i++)
14. {
15. if($i%2 != 0)
16. {
17. for($j=5; $j>=$i; $j--)
18. {
19. echo "* ";
20. }
21. echo "<br>";
22. }
23. }
24. ?>

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy