BIT3105 INTERNET PROGRAMMING Notes Final
BIT3105 INTERNET PROGRAMMING Notes Final
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: -
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
Week 1: Introduction
Introduction to XML
XML Tree
XML Syntax
XML Elements
XML Attributes
XML Validation
XML Validator
XML CSS
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
MySQL Introduction
MySQL Connect
MySQL Create
MySQL Insert
MySQL Select
MySQL Where
MySQL Order By
7
MySQL Update
MySQL Delete
PHP Include
PHP File
PHP File Upload
PHP Cookies
PHP Sessions
PHP E-mail
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.
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>
</body>
</html>
HTML Different Doctypes
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.
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.
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.
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.
This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.
<html>
<head>
<title> My first page </title>
</head>
<body>
The content of the
document......
</body>
</html>
<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>
<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.
<script type="text/javascript">
document.write("Hello World!")
</script>
Non-breaking Space
A common character entity used in HTML is the non-breaking space ( ).
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 character entity.
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>
</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>
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:
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:
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>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for
learners");
</script>
</body>
</html>
<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.
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.
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
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).
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
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
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.
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:
There are five types of primitive data types in JavaScript. They are as follows:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
Operator
Description Example
&& Logical AND
(10==20 && 20==33) = false
Logical OR(10==20 || 20==33) = false
Logical Not
!(10==20) = true
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>
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.
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
1. for loop
2. while loop
3. do-while loop
4. for-in 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.
Example
<script>
Var i;
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5
while (condition)
{
code to be executed
}
Example
<script>
var i=20;
while (i>=0)
{
document.write(i + "    ");
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
Function Syntax
Function Example
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Function 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>
<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.
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.
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
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).
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
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
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.
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:
There are five types of primitive data types in JavaScript. They are as follows:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
2. var sum=10+20;
7. Arithmetic Operators
8. Comparison (Relational) Operators
9. Bitwise Operators
10. Logical Operators
11. Assignment Operators
12. Special 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
The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
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>
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.
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.
5. for loop
6. while loop
7. do-while loop
8. for-in 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.
Example
<script>
Var i;
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5
while (condition)
{
code to be executed
}
Example
<script>
var i=20;
while (i>=0)
{
document.write(i + "    ");
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
Function Syntax
Function Example
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Function 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?
XML
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 data can also be stored inside HTML pages as “Data Islands”.
You can still concentrate on using HTML for formatting and displaying the 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 version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget to come for the class this weekend!</body>
</note>
XML tree
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>
Company
Employee
xml elements
In HTML some elements do not have to have a closing tag. Eg
<p>This is a paragraph
<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>
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
To avoid this error, replace the "<" character with an entity reference:
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.
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
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>
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
Eg
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.
The second line links the XML file to the CSS file:
INTRODUCTION TO PHP
What is PHP?
<?php
// PHP code goes here
?>
<!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 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>
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.
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
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo"<br>";
echo $y;
?>
PHP 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.
Syntax
<?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
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!";
}
?>
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
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++;
}
?>
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
<?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);
?>
<?php
for ($x = 0; $x <= 10; $x++){
echo"The number is: $x <br>";
}
?>
<?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
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:
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
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.
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
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
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:
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.
Output:
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
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
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";
?>
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.
Output:
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:
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.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
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
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
Syntax
EG
Syntax
bool mysqli_close(resource $resource_link)
<?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
The query above selects all the data in the "LastName" column from the "Employees"
table.
PHP Create 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
$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);
}
$conn->close();
?>
</body>
</html>
PHP Insert Data Into MySQL
The INSERT INTO statement is used to add new records to a MySQL table:
<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);
}
$conn->close();
?>
</body>
</html>
Another example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
mysqli_close($conn);
?>
The SELECT statement is used to select data from one or more tables:
<?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);
}
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();
?>
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);
}
$conn->close();
?>
PHP Update Data in MySQL
Update Data In a MySQL 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:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_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
Table of Number
A table of a number can be printed using a loop in program.
Logic:
Example:
<?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:
Example:
<?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:
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.
Example:
<?php
$number=1233456;
if($number%2==0)
{
echo "$number is Even Number";
}
else
{
echo "$number is Odd Number";
}
?>
Output:
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:
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.
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:
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 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:
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:
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.
For example,
Logic:
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.
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:
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:
Output:
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:
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:
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:
Output:
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.
Logic:
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:
For example
1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20
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:
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:
<?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:
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:
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,
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,
Logic:
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.
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:
Logic:
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:
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: