0% found this document useful (0 votes)
375 views233 pages

MyPhp Materials

The document discusses JavaScript development tools. It describes the features and capabilities of Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 - popular tools used for JavaScript and web development. FrontPage provided JavaScript tools and dynamic web templates. Dreamweaver supported coding, site management, and standards compliance. HomeSite allowed direct coding and was scriptable but was later discontinued after being acquired by Macromedia.

Uploaded by

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

MyPhp Materials

The document discusses JavaScript development tools. It describes the features and capabilities of Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 - popular tools used for JavaScript and web development. FrontPage provided JavaScript tools and dynamic web templates. Dreamweaver supported coding, site management, and standards compliance. HomeSite allowed direct coding and was scriptable but was later discontinued after being acquired by Macromedia.

Uploaded by

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

ELLECTIVE - PHP & SCRIPTING LANGUAGES

UNIT I:
VB Script and Java Script: Language structure - control structure - Procedures and
functions - Error handling.

UNIT II:
VB Script: Input & Output - Data Validation -Integration with Forms – Activex Control
& Scripting

UNIT III:
Java Script: Form Validation – SSI and Cookies – Frames and Windows – MIME Types -
Plugins

UNIT IV:
PHP: Server side scripting Language: Basic syntax - Types - Variables - Constants -
Expressions - Operators - Control Structures

UNIT V
PHP : Functions - Classes and Objects - HTML forms - HTTP authentication with PHP -
Cookies - Handling file uploads - Using remote files - Connection handling - Database
Connections.

TEXT BOOKS:
1. Christopher J.Goddard, Mark White, Mastering VB Script‖, Galgotia publications, New Delhi.
2. Lee Purcell, Mary Jane Mara, ―The ABCs of Javascript‖,
3. Steven Holzner, ―PHP: The Complete Reference‖
Index Page (PHP)

Example

Total Number

Total Number
Starting Page

of Programs
Ending Page
Particulars

Programs

of Pages
Units

Starting Ending
No. No.
JavaScript

1 47 47 1 40 40
I

VBScript

48 84 37 41 80 40
VBScript
II

85 101 17 81 91 11
JavaScript
III

102 122 21 92 104 13


PHP
IV

123 155 33 105 150 46


PHP

156 214 59 151 203 53


V

General
215 229 15 204 207 4
Topics
Unit-I

JAVA SCRIPT
Java Script was released by Netscape and Sun Micro system in the year 1995, Java script is not similar like java.

DEFINE JAVA SCRIPT


• JavaScript life as Live Script but Netscape changed the name, possibly because as the Excitement
being generate by Java to Java Script.
• Java Script made its first appearance in Netscape version 2.0 1995 with a name Live script.
• Java Script is a lightweight, interpreted Programming Language and designed for creative network-
satiric applications for complementary and integrated such as Java HTML.
• Open and Cross platform, it’s widely used for supported. It is accessible due to beginner.

USE OF JAVA SCRIPT It used to add multimedia elements

CLIENT-SIDE
Client-side JavaScript is the most common form of the language. The script should be included in HTML
document for code to be interpreted by the browser. Web pages need not be a static HTML, it can include
programs interact with the user, control the browser, and dynamically create HTML content. JavaScript
code is executed when the user submits the form, and only if all the entries are valid, they would be
submitted to the Web Server. JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

ADVANTAGES OF JAVASCRIPT
• Less server interaction can validate user input before sending the page off to the server. This saves
server traffic, which means fewer loads on your server.
• Immediate feedback to the visitors they don't have to wait for a page reload to see if they have
forgotten to enter something.
Nandha Arts and Science College PHP – I Unit BCA Department

• Increased interactivity can create interfaces that react when the user however over them with a
mouse or activates them via the keyboard.
• Richer interfaces can use JavaScript to include such items as drag-and-drop components and sliders
to give a Rich Interface to your site visitors.

LIMITS OF JAVASCRIPT- It cannot a full-fledged programming language will lack some features−

1. Client-side JavaScript does not allow the reading or writing of files.


2. JavaScript cannot be used for networking applications because there is no such support available.
3. JavaScript doesn't have any multithreading or multiprocessor or capabilities.

Development Tools
The major strengths of JavaScript are not required expensive development tools, will start with a simple text
editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don't
even need to buy a compiler. To make our life simpler, various editing tools are presently outcome.

Microsoft FrontPage
FrontPage also provides
web developers with a
number of JavaScript tools
to assist in the creation of
interactive websites. It was
branded as part of the MS
Office suite from 1997 to
2003. First released in Dec.
2006. MS FrontPage has
since been replaced by MS
Expression Web &
SharePoint Designer, along MS Office`97.
Features
FrontPage 2003 consists of a Split View option to allow the user to code in Code View and preview in Design
View without the hassle of switching from the Design and Code View tabs for each review. Dynamic Web
Templates (DWT) were included for the first time in FrontPage 2003 allowing users to create a single
template that could be used across multiple pages and even the whole Web site. Interactive Buttons give
users a new easy way to Create Web graphics for navigation and links.

Java Script 2
Nandha Arts and Science College PHP – I Unit BCA Department

Macromedia Dreamweaver MX
Dreamweaver was created by Macromedia in 1997, and was maintained by them until Macromedia
was acquired by Adobe Systems in 2005. Macromedia Dreamweaver MX is an easy, powerful, and
open authoring tool that every
member of the development
team can use to quickly build
robust websites and Internet
applications. Macromedia
Dreamweaver MX is a very
popular HTML and JavaScript
editor in the professional web
development crowd. It provides
several handy prebuilt JavaScript
components, integrates well
with databases, and conforms to
new standards.

Features
Dreamweaver is a web design and
development application that
combines a visual design surface
known as Live View and a code
editor with standard features such
as syntax highlighting, code
completion, and code collapsing. Combined with an array of site management tools, Dreamweaver lets its users
design, code and manage websites as well as mobile content.
Dreamweaver supports syntax highlighting for the following languages
Action Script, Active Server Pages (ASP),C#, Cascading Style Sheets (CSS), ColdFusion, Extensible Hypertext Markup
Language (XHTML), Extensible Markup Language (XML), Extensible Style sheet Language Transformations (XSLT),
Hypertext Markup Language (HTML), JavaScript, PHP, Visual Basic Script Edition (VBScript) and Wireless Markup
Language (WML).

Java Script 3
Nandha Arts and Science College PHP – I Unit BCA Department

Macromedia HomeSite 5
HomeSite was an HTML editor originally developed by Allaire
Corporation. Unlike WYSIWYG (what you see is what you get), HomeSite were designed for direct
editing, or "hand coding," of HTML and JavaScript other website languages. After a successful
partnership with the company to
distribute it alongside its own
competing Dreamweaver
software, HomeSite was acquired
by Macromedia in 2001, after
which elements of the software
were integrated into
Dreamweaver. Following the
acquisition of Macromedia by
Adobe Systems, the company
announced on May 26, 2009 that
HomeSite would be discontinued.
Features
a. Extensively script-able to automate tasks or to perform advanced tasks using JavaScript or VBScript.
b. Macro recorder can record a series of actions to create scripts for later playback
c. Enhanced code snippets save time by creating and saving reusable blocks of code, and can prompt for
variable replacement when used.
d. Customizable syntax color-coding for ASP, CFML, CSS, HTML, Java, JavaScript, JSP, Perl, PHP, SQL,
VBScript, VTML and XHTML. Syntax-coloring parser syntax and examples are available to help users.
e. Search and replace utility
f. CSS editing via the included Top Style Lite, or via integration with the full version of Top Style, if available,
check your code with the built-in Code Validator, or use CSE HTML Validator with UI integration.
g. Integrated help browser shows installed help docs or HTML-format document sets added by the user. Useful for
local, searchable copies of standards, tutorials, language references, etc.
h. Project management and built-in FTP help manage and upload websites
i. Built-in tools for page link-checking, document weight and spell-checking
j. XHTML 1.0 Support

Java Script 4
Nandha Arts and Science College PHP – I Unit BCA Department

ECMA Script (History)


The ECMAScript specification is a standardized specification of a scripting language
developed by Brendan Eich of Netscape; initially it was named Mocha, later LiveScript, and
finally JavaScript. In December 1995, Sun Microsystems and Netscape announced JavaScript
in a press release. The first edition of ECMA-262 was adopted by the ECMA General
Assembly in June 1997. Several editions of the language standard have been published since
then. The name "ECMAScript" was a compromise between the organizations involved in
standardizing the language, especially Netscape and Microsoft, whose disputes dominated
the early standards sessions. Eich commented that "ECMAScript was always an unwanted
trade name that sounds like a skin disease."
• While both JavaScript and JScript aim to be compatible with ECMAScript, they also provide
additional features not described in the ECMA specifications.
• ECMAScript is a standard script language, developed with the cooperation of Netscape and
Microsoft and mainly derived from Netscape's JavaScript, the widely-used scripting language
that is used in Web pages to affect how they look or behave for the user. Microsoft states
that its latest version of JScript is the first implementation of the ECMAScript standard. The
official standard, ECMA-262, was developed under the auspices of the European Computer
Manufacturers Association (ECMA).
• The ECMAScript specification is a standardized specification of a scripting language
developed by Brendan Eich of Netscape; initially it was named Mocha, later LiveScript, and
finally JavaScript. In December 1995, Sun Microsystems and Netscape announced
JavaScript in a press release. In March 1996, Netscape Navigator 2.0 was released, featuring
support for JavaScript.
• JScript was included in Internet Explorer 3.0, released in August 1996.
• JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
• ECMAScript is the official name of the language.
• From 2015 ECMAScript is named by year (ECMAScript 2015).
Latest June 2018 ECMAScript 2018 (ES2018) 9th Edition

Java Script 5
Nandha Arts and Science College PHP – I Unit BCA Department

Ver Official Name Description


1 ECMAScript 1 (1997) First Edition.
2 ECMAScript 2 (1998) Editorial changes only.
3 ECMAScript 3 (1999) Added Regular Expressions. , Added try/catch.
4 ECMAScript 4 Never released.
Added "strict mode". Added JSON support. Added String.trim().
5 ECMAScript 5 (2009)
Added Array.isArray().Added Array Iteration Methods.
5.1 ECMAScript 5.1 (2011) Editorial changes.
Added let and const. Added default parameter values.
6 ECMAScript 2015
Added Array.find(). Added Array.findIndex().
7 ECMAScript 2016 Added exponential operator (**).Added Array.prototype.includes.
Added string padding. Added new Object properties.
8 ECMAScript 2017
Added Async functions. Added Shared Memory.
Added rest / spread properties. Added Asynchronous iteration.
9 ECMAScript 2018
Added Promise.finally(). Additions to RegExp.
What is different between “= = “and “= = =”.
While “= =” checks only for equality, “= = =” checks for equality as well as the type.

WRITING JAVA SCRIPT


Java script code is difficulty embedded in the HTML, to be interpreted and run by the client browser.
❖ Java script is case-sensitive.
❖ White space between words and tabs are ignoring.
❖ Line breaks are ignored except within a statement.
❖ Java script statements end with semi-colon (;).

JAVA VS JAVA SCRIPT


JAVA JAVA SCRIPT
Java invented by James Gosling and Sun Microsystems Java Script invented by Brendan Eich.

Java Powered by Sun Micro System, Open JDK, many others Java Script powered by Netscape Navigator

Java released in 1995 Java Script released in 1995


Java score must have parsed, compiled (not interpreter)
into object code can be run any platform (operating system Java Script codes are interpreter language
& not necessary a browser) having the JRE.
Java creates an application that runs java virtual machine or browser. Java programs runs in only Web-browser
Java is an OOPS programming language. Java script is an OOPS script language.
Java program code executed by compiled to byte code Java Script Codes are all in text, does not need to be compiled

Java programs statement terminated by Semicolon(;) Java Script programs also same
Java codes needs to be complied Java Script code all in text they require different plug-in.

Java Script 6
Nandha Arts and Science College PHP – I Unit BCA Department

THE SCRIPT TAG:


• JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page. You can place the <script> tags, containing your JavaScript, anywhere
within you web page, but it is normally recommended that you should keep it within the <head> tags.
• The <script>tag alerts the browser program to start interpreting all the text between these tags as a
script. A simple syntax of your JavaScript will appear as follows.

SYNTAX OF JAVASCRIPT
<SCRIPT>
Statements; </Script> (or)
<SCRIPT language = “JavaScript”>
Statements; </Script> (or)
<Script Language = "JavaScript" type = "text/JavaScript">
Java script code; </Script>
The script tag takes are important attributes:
• Language − This attribute specifies what scripting language you are using. Typically, its value will be JavaScript.
Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/JavaScript".
• src − The location of an external scripting file

Example – 01
<html> <title> Java Script Program </title>
<body>
<script language="JavaScript" type ="text/JavaScript">
<!--
document.write("This is My First JavaScript Program");
//-->
</script>
This is My First
</body> JavaScript Program
</html>

Java Script 7
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 02
<Html>
<title> My detail </title>
<body>
<Script language="JavaScript" type="text/JavaScript">
<!--
document.write("Name: Raja")<<"br/">
document.write<"DOB: 22-01-1996")<<"br/">
document.write<"Aim: Program Developer">
//--> Name: Raja
</script> DOB: 22-01-1996
</body> Aim: Program Developer
</html>

parseInt("10") 10 parseInt("10.00") 10 parseFloat()


parseInt("10.33") 10 parseInt("34 45 66") 34 parseInt()
parseInt(" 60 ") 60 parseInt("40 years") 40
parseInt("He was 40") NaN parseInt("10", 10) 10
parseInt("010") 10 parseInt("10", 8) 8
parseInt("0x10") 16 parseInt("10", 16) 16
NaN - Not-a-Number"

Example – 03
<html> Enter the First No. : 10
Enter the Second No. : 20
<title>Add two Number</title> Sum = 30
<body>
<Script language="JavaScript "type="text/JavaScript">
<! -- var N1,N2,sum;
N1= prompt("Enter the First No")
N2 = prompt("Enter the Second No")
Sum = parseInt (N1)+ parseInt(N2) alert ("sum="+sum)
//-->
</Script>
</body>
</html>

Java Script 8
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 04
<html> <title> Arithmetic </title>
<body> <script language="java script" type="text/JavaScript">
<!-- var N1, N2, Sum, Sub, Mul, Div;
N1 = prompt("Enter the First Number:")
N2 = prompt("Enter the Second Number:")
Sum = parseInt(N1) + parseInt(N2)
Sub = parseInt(N1) - parseInt(N2) Enter the First No. : 20
Enter the Second No.: 10
Mul = parseInt(N1) * parseInt(N2)
Sum = 30
Div = parseInt(N1) / parseInt(N2) Subtract = 10
alert("SUM =" + Sum) Multiply = 200
alert("SUB =" + Sub) Division = 2

alert("MUL =" + Mul)


alert("DIV =" + Div)
//--> </script> </body> </html>
CHANGE THE BG COLOR AND FORE COLOR:
<Script document.bgcolor = "Green" document.fgcolor = "Red" # "336899">
</Script>
MeSSAGE BOX (OR) POPUP MESSAGE BOX :
There are 3 message boxes: 1) alert 2) confirm 3) prompt
Alert: <Script window.alert("Welcome to My Web Page")></Script>
Confirm: <Script window.confirm("Are You Sure want to Quit")></Script>
Prompt: <Script window.prompt(" Please Enter Your Name")></Script>

WHITE SPACES AND LINE BREAKS:


Java Script ignores spaces, tabs and new lines that appear in java script programs. Because you can use
spaces, tabs and new line freely in your program so you are free to format and indent your programs in a
neat and consistent use that makes the code easy to read and understand.

Java Script 9
Nandha Arts and Science College PHP – I Unit BCA Department

SEMI-COLON (;) OR OPTIONAL:


• Simple statements in java script are generally followed by a semi-colon(;) character
• Java script, however allows you to omit this semi-colon(;) if your statement are each placed on a separate line.
<Script language = "Java Script" type = "text/java script">
<!—
var n1= 10; var n2 = 20 //--> (or) <!-- var n1 = 10, n2 =20;
//-->
CASE SENSITIVE:
Java Script is a case sensitive language. This means that language keywords, variable, functions name and
any other identifiers must always be typed a consistent capitalization of letters.
COMMENTS IN JAVA SCRIPT:
JavaScript comments can also be used to prevent execution, when testing alternative code.
1. Single line comments start with //. 2. Multi-line comments start with /* and end with */.
ENABLING JAVASCRIPT IN BROWSERS
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or
disable this support manually. The procedure of enabling and disabling JavaScript support in your browsers:
Internet Explorer, Firefox, chrome, and Opera.
JAVASCRIPT IN INTERNET EXPLORER Here are simple steps to turn on or turn off JavaScript in your IE
• Follow Tools → Internet Options from the menu. • Select Security tab from the dialog box.
• Click the Custom Level button. • Scroll down till you find Scripting option.
• Select Enable radio button under Active scripting. • Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

WARNING FOR NON-JAVASCRIPT BROWSERS


If you have to do something important using JavaScript, then you can display a warning message to the user
using <noscript> tags. You can add a no script block immediately after the script block as follows –

Example - 05
<html> <body>
<script language = "javascript" type = "text/javascript">
<!-- document.write("Hello World!") //-->
Script Enabled
</script>
<noscript> Sorry...JavaScript is needed to go ahead. </noscript>
</body> </html>

Java Script 10
Nandha Arts and Science College PHP – I Unit BCA Department

Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from
</noscript> will be displayed on the screen.

JavaScript - Placement in HTML File


There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most
preferred ways to include JavaScript in an HTML file are as follows −
• Script in <head>...</head> section. • Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
JAVASCRIPT IN <HEAD>...</HEAD> SECTION
If you want to have a script run on some event, such as when a user clicks somewhere, then you will place
that script in the head as follows −

Example - 06 Hello World

<html> <head>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- functionsayHello()
{ alert("Hello World") }
//--> </script> </head> <body>
<input type="button" onClick="sayHello()" value= "Say Hello"/>
</body> </html>

JAVASCRIPT IN <BODY>...</BODY> SECTION


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

Example - 07
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
Welcome
<!-- document.write("Welcome to JavaScript") to
//--> JavaScript
</script>
<p>This is web page body </p>
</body> </html>

Java Script 11
Nandha Arts and Science College PHP – I Unit BCA Department

JAVASCRIPT IN <BODY> AND <HEAD> SECTIONS


Example - 08
<html> <head>
<script language = “JavaScript” type=“text/JavaScript”> Hello World
<!-- Hello World
function sayHello()
{
alert("Hello World")
}
//--> </script> </head>
<body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
document.write("Hello World") //-->
</script>
<input type="button" onClick="sayHello()"value="Say Hello"/>
</body> </html>

JAVASCRIPT IN EXTERNAL FILE


This is advantageous to group common functions in an external JavaScript file. This permits the reuse of the
functions in the file in multiple HTML pages. JavaScript functions are stored in a file using the .js extension. Here
is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute.

Example – 09 // functions.js
function multiply(num1, num2) 12
{ return num1*num2; }
//Index1.html
<html> <head>
<title> JavaScript Example</title>
<script language = “JavaScript" src="functions.js">
</script> </head>
<body>
<script type="text/JavaScript">
document.write(multiply(3,4));
</script> </body> </html>

Java Script 12
Nandha Arts and Science College PHP – I Unit BCA Department

JAVASCRIPT –VARIABLES
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language. Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword,

Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _ (but we will not use it in this tutorial)
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var money; (or) var money, name; (or)var money= 5000.00;
var name; var name= “Raja”;
//--> </script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of
variable creation or at a later point in time when you need that variable.

JAVASCRIPT DATA TYPES


One of the most fundamental characteristics of a programming language is the set of data types it supports. These
are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
• Numbers, e.g.123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
JavaScript also defines two trivial (small) data types, null and undefined, each of which defines only a single
value. In addition to these primitive data types, JavaScript supports a composite data type known as object.

Java Script 13
Nandha Arts and Science College PHP – I Unit BCA Department

JAVASCRIPT IS Untype LANGUAGE.


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

JAVASCRIPT VARIABLE SCOPE


The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local variables− A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare
a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.

Example – 10
<script language = "Java Script” type ="text/Java Script">
<!—
var myvar= "Global" //declare a global variable
function classA() myvar: Local

{ MYVAR: Global
var myvar = "Local" // declare a local variable
document.write("myvar"+ myvar); }
document.write(“MYVAR” + myvar);
//-->
</script>

JAVA SCRIPT VARIABLE NAME:


While naming your variables in java script keep following rules in mind.
• You should not use any of the java script reserved keyword as variable name.
• Java Script variable name should not start with a numeral(0...9). They must begin with a letter or the
underscore(_ ) character. For Example -123test, it not valid _123test it's a valid.
• Java Script variable names are case-sensitive.

JAVASCRIPT RESERVED WORDS


A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript
variables, functions, methods, loop labels, or any object names.

Java Script 14
abstract delete function null throw
boolean do goto package throws
break double if private transient
byte else implements protected true
case enum import public try
catch export in return typeof
char extends instanceof short var
class false int static void
const final interface super volatile
continue finally long switch while
debugger float native synchronized with
default for new this
JAVASCRIPT - OPERATORS
WHAT IS AN OPERATOR?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational) Operators
✓ Bitwise Operator
4. Assignment Operators
5. Miscellaneous Operators
✓ Conditional (or Ternary) Operators
✓ Typeof operator

1. ARITHMETIC OPERATORS: Assume A=10, B=20


Operator Description Example
+ Adds two operands. A+B=30
- Subtract second operand from the first. B-A=10
* Multiply the both operands. A*B=200
/ Divide numerator by divider. B/A=2
% Module Operator. B%A=0
++ Increment Operator. Increase integer value by one. A++=11
-- Decrement Operator. Decrease integer value by one. A--=9
Nandha Arts and Science College PHP – I Unit BCA Department

Example - 11
<html> results= a * b;

<body> document.write(results);

<script type= “text/JavaScript”> document.write(linebreak);

<!— a =++a;

var a =33, b =10, results; document.write("++a = ");

var linebreak="<br />"; results=++a;

document.write(“Arithmetic document.write(results);

Operator Program”); document.write(linebreak);

document.write("a + b = "); b =--b;

results= a + b; document.write("--b = ");

document.write(results); results=--b;

document.write(linebreak); document.write(results);

document.write("a - b = "); document.write(linebreak);

results= a - b; //-->

document.write(results); </script>

document.write(linebreak); </body>

document.write("a / b = "); </html>

results= a / b;

document.write(results);

document.write(linebreak);

document.write("a % b = "); Arithmetic Operator Program


Output
results= a % b;
a + b = 43 a - b = 23 a / b = 3.3
document.write(results); a%b=3 a * b = 330
Test
document.write(linebreak); ++a = 35 --b = 8

document.write("a * b = ");

Java Script 16
Nandha Arts and Science College PHP – I Unit BCA Department

2. COMPARISON OPERATOR: Assume A=10, B=20


Operator Description Example
Check if the value of two operands is equal or not, if yes condition
== A= = B = False
become true.
Check the value of two operands are equal are not, if values are not
!= (A!=B) = True
equal condition become true.
Check if the value of left operand is greater than the value of right
> (A>B) = False
operand if yes condition become true.
Check if the value of left operand is less than the value of right operand
< (A<B) =True
if yes condition become true.
Check if the value of left operand is greater than or equal the value of
>= (A>=B) = False
right operand if yes condition become true.
Check if the value of left operand is less than or equal the value of right
<= (A<=B) = True
operand if yes condition become true.

Example -12
<html>
<body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- document.write(results);
var a =10, b =20 results; document.write("(a >= b) => ");
var linebreak="<br />"; results = (a >= b);
document.write(“Comparison document.write(results);
Operations Program”); document.write("(a <= b) => ");
document.write("(a == b) => "); results = (a <= b);
results = (a == b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); //--> </script> </body> </html>
document.write("(a < b) => ");
results = (a < b);
Comparison Operator Program
document.write(results); Output
(a == b) => false
document.write("(a > b) => ");
(a < b) => true
results = (a > b); (a > b) => false
(a != b) => true
document.write(results); (a >= b) => false
document.write("(a != b) => "); a <= b) => true
results = (a != b);

Java Script 17
Nandha Arts and Science College PHP – I Unit BCA Department

3. LOGICAL OR RELATIONAL OPERATOR: Assume A=10, B=20


Operator Description Example

&& "AND" operator. If both operands are non-zero then condition becomes true. (A&&B) = True
||
"OR" operator is any one operandis non-zero then condition becomes true. (A||B) =True

! "!" operator called logical not operator. Use to reserves the logical operator make false. !(A&&B) = False

Example – 13
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var a = true, b =false results; document.write(linebreak);
var linebreak="<br />"; document.write("!(a && b) => ");
document.write(“Logical Or results=(!(a && b));
Relational Operator”); document.write(results);
document.write("(a && b) => "); document.write(linebreak);
results=(a && b); //--> </script> </body> </html>
document.write(results);
document.write(linebreak); Logical or Relational Operator
document.write("(a || b) => ");
results=(a || b); (a&& b) => false (a || b) => true !(a && b) => true
document.write(results);

3.1 BITWISE OPERATOR: Assume A=2, B=3


Operator Description Example

& Bitwise "AND" operator. It performs a Boolean AND operation on each bit of its integer (A&B) is 2
argument.
| Bitwise "OR" operator. It performs a Boolean OR operation on each bit of its integer (A|B) is 3.
argument.
A Bitwise "XOR" operator. It performs a Boolean Exclusive OR operation on each bit of its (AAB) is 1.
integer argument.
~ Bitwise "NOT" operator. It unary operator and operates by reversing all bits in the operand. (~B) is -4

<< Bitwise "Shift Left Operator" It moves all bits in its first operand to the left by the number (A<<1) is 4
of places specified in the second operand.
>> Bitwise "Shift Right Operator" It moves all bits in its first operand to the right by the (A>>1) is 1.
number of places specified in the second operand.
>>> Bitwise "Shift Right with Zero Operator. This operator just like the >> operator, except that (A>>>1) is 1.
the bits shifted in on the left are always zero.

Java Script 18
Nandha Arts and Science College PHP – I Unit BCA Department

And (&) (Multiply) Or (ADD) XOR


0 0 ----> 0 0 0
0 1 ----> 0 1 1
1 0 ----> 0 1 1
1 1 ----> 1 1 0
Example
A = 2, B=3 (&) A = 2, B=3 (|)
A = 0010 2 A = 0010 2
B = 0011 3 B = 0011 3
(A&B) 0010 2 (A|B) 0011 3

A = 2, B=3 (^) B=3 (~)


A = 0010 2 B = 0011 3
B = 0011 3 (2's Complement + 1) 1 1
(A^B) 0001 1 Answer 0100 4
(Positive Number
Multiply into -1) (0100 * -1) -4
(~B) -0100 -4
A=2 (<<) A=2 (>>)
A = 0010 2 A = 0010 2

(A<<1) 00100
4 (A>>1) 00010
1
0 left to right
side move
(A<<1) 0100 4 (A>>1) 0001 1
A=5 (>>>) A = 10 (>>>)
A = 0101 5 A = 1010 10
2 5
(A>>>5) 00101 (A>>>5) 01010

(A>>>5) 0010 2 (A>>>5) 0101 5

Java Script 19
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 14
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var a =2;// Bit presentation 10 results=(~b);
var b =3;// Bit presentation 11 document.write(results);
var results, linebreak="<br />"; document.write(linebreak);
document.write(“Bitwise operator”); document.write("(a << 1) => ");
document.write("(a & b) => "); results=(a << b);
results=(a & b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); document.write("(a >> 1) => ");
document.write("(a | b) => "); results=(a >> b);
results=(a | b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); //--> </script> </body> </html>
document.write("(a ^ b) => ");
results=(a ^ b); Bitwise operator
document.write(results); (a& b) => 2 (a | b) => 3
document.write(linebreak); (a ^ b) => 1 (~b) => -4
document.write("(~b) => "); (a << 1) => 4 (a >>1) => 1

4. ASSIGNMENT OPERATOR:
Operator Description Example

= Assigns values from right side operands to left side operand. C=A+B will assign value of A+B into C

+= Add AND assignment operator, it adds right operand to the left C+= A is equal to C=C+A
operand and assign the results to left operand.

-= Subtract AND assignment operator, it Subtract right operand to C-= A is equal to C=C-A
the left operand and assign the results to left operand.

*= Multiply AND assignment operator, it Multiplies right operand C*= A is equal to C=C*A
to the left operand and assign the results to left operand.

/= Divide AND assignment operator, it divides left operand with C/= A is equal to C=C/A
the right operand and assign the results to left operand.

%= Modulus AND assignment operator, it takes modulus using two C%=A is equal to C=C%A
operands and assign the results to left operand.

Java Script 20
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 15
<html> <body> <script language = “JavaScript” type=“text/JavaScript”>
<!-- document.write("Value of a => (a *= b) => ");

var a =10, b = 30, results; results=(a *= b);

var linebreak="<br />"; document.write(results);

document.write(“Assignment Operator”); document.write(linebreak);


document.write("Value of a => (a = b) => "); document.write("Value of a => (a /= b)=> ");

results=(a = b); results=(a /= b);


document.write(results); document.write(results);
document.write(linebreak); document.write(linebreak);
document.write("Value of a => (a += b)=>"); document.write("Value of a => (a %= b) => ");

results=(a += b); results=(a %= b);


document.write(results); document.write(results);
document.write(linebreak);
Assignment Operator
document.write("Value of a =>(a-= b)=> "); //-->
Value of a => (a = b) => 30
results=(a -= b); </script> Value of a => (a += b) => 60
Value of a => (a -= b) => 30
document.write(results); </body>
Value of a => (a *= b) => 900
document.write(linebreak); </html> Value of a => (a /= b) => 30
Value of a => (a %= b) => 0

5. MISCELLANEOUS OPERATOR The Conditional Operator (?:)


Operator Description Example
?: Conditional Expression If Condition is true? Then value X: Otherwise Value Y

Example – 16
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var a =1, b =2; var linebreak="<br />";
document.write("((a > b) ?50 : 100) => ");
results=(a > b)?50:100; Output
document.write(results); ((a > b) ? 50 : 100) => 100
document.write(linebreak); ((a < b) ? 50 : 100) => 50
document.write("((a < b) ?50 : 100) => ");
results=(a < b)?50:100;
document.write(results); //--> </script> </body> </html>

Java Script 21
Nandha Arts and Science College PHP – I Unit BCA Department

The Typeof Operator


Type String Returned by Typeof

Number "number"
String "string"
Boolean "Boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example – 17
The following code shows how to implement typeof operator.
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> Output
<!-- Result => y is String
var x =10, y ="String";
Result => x is Numeric
var linebreak="<br />";
results=(typeof y =="string"?" y is String": "y is Numeric");
document.write("Result => ");
document.write(results);
document.write(linebreak);
results=(typeof x =="string"? "x is String": "x is Numeric");
document.write("Result => ");
document.write(results);
document.write(linebreak);
//-->
</script>
</body>
</html>

JAVASCRIPT - if...else STATEMENT


While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In
such cases, you need to use conditional statements that allow your program to make correct decisions and
perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different
conditions. Here we will explain the if..else statement.

Java Script 22
Nandha Arts and Science College PHP – I Unit BCA Department

FLOW CHART IF-ELSE


The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if...else statement
• if statement

• if...else statement

• if...else if... statement.

IF STATEMENT
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax The syntax for a basic if statement is as follows −
If (expression) { Statement(s) to be executed if expression is true }
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If
the expression is false, then no statement would be not executed. Most of the times, you will use comparison
operators while making decisions.

Example – 18
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var age =20;
Output
if( age >18){
document.write("<b> Qualifies for driving</b>"); Qualifies for driving

} //--> </script> </body> </html>

IF...ELSE STATEMENT:
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in
a more controlled way.
Syntax
if(expression){
Statement(s) to be executed if expression is true
}
else {
Statement(s) to be executed if expression is false
}

Java Script 23
Nandha Arts and Science College PHP – I Unit BCA Department

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block,
are executed. If the expression is false, then the given statement(s) in the else block are executed.

Example – 19
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var age =15;
if(age>18) Output
{ Does not qualify for
document.write("<b>Qualifies for driving</b>"); driving

}
else
{
document.write("<b>Does not qualify for driving</b>");
}
//--> </script> </body> </html>

IF...ELSE IF... STATEMENT


The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision
out of several conditions.
Syntax :
if(expression 1){
Statement(s) to be executed if expression 1 is true
}
elseif(expression 2){
Statement(s) to be executed if expression 2 is true
}
elseif(expression 3){
Statement(s) to be executed if expression 3 is true
}
else{
Statement(s) to be executed if no expression is true
}

Java Script 24
Nandha Arts and Science College PHP – I Unit BCA Department

There is nothing special about this code. It is just a series of if statements, where each if is a part of the else
clause of the previous statement. Statement(s) are executed based on the true condition, if none of the
conditions is true, then the else block is executed.

Example – 20
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var book ="C";
if( book =="C++"){
document.write("<b> C++ Book</b>"); Output
} C Book
elseif( book =="Java"){
document.write("<b> Java Book</b>");
}
elseif( book =="C"){
document.write("<b> C Book</b>");
}
else{
document.write("<b>Unknown Book</b>");
}//--> </script> </body> </html>

JavaScript - Switch Case


You can use multiple if...else…if statements, as in the previous section, to perform a multi way branch.
However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable. Starting with JavaScript
1.2, you can use a switch statement which handles exactly this situation,
and it does so more efficiently than repeated if...else if statements.
Syntax
The objective of a switch statement is to give an expression to evaluate
and several different statements to execute based on the value of the
expression. The interpreter checks each case against the value of the
expression until a match is found. If nothing matches, a default condition
will be used.

Java Script 25
Nandha Arts and Science College PHP – I Unit BCA Department

switch(expression)
{
case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
...
case condition n:
statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would
continue executing each statement in each of the following cases.

Example – 21
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var grade='A';
document.write("Entering switch block <br />");
switch(grade)
{ Output
case'A':document.write("Gold Medal <br />");
break;
Entering switch block
case'B':document.write("Distinction <br />");
Gold Medal
break;
Exiting switch block
case'C':document.write("First Class <br />");
break;
case'D':document.write("Second Class <br />");
break;
case'E':document.write("Third Class <br />");
break;
case'F':document.write("Failed <br />");
break;
default: document.write("Unknown grade <br />")
}
document.write("Exiting switch block");
//--> </script> </body> </html>

Java Script 26
Nandha Arts and Science College PHP – I Unit BCA Department

BREAK STATEMENTS
Break statements play a major role in switch-case statements. Try the following code that uses switch-case
statement without any break statement.

Example – 22
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var grade='A';
document.write("Entering switch block<br />");
Output
switch(grade){
Entering switch block
case'A':document.write("Gold Medal <br />"); Gold Medal
Distinction
case'B':document.write("Distinction <br />");
First Class
case'C':document.write("First Class <br />"); Second Class
Third Class
case'D':document.write("Second Class <br />"); Failed
case'E':document.write("Third Class <br />"); Unknown grade
Exiting switch block
case'F':document.write("Failed <br />");
default:document.write("Unknown grade <br />")
}document.write("Exiting switch block");
//--> </script> </body> </html>

JAVASCRIPT - WHILE LOOPS


While writing a program, you may encounter a situation where you need to perform an action over and over again. In
such situations, you would need to write loop statements to reduce the number of lines.

THE WHILE LOOP


The most basic loop in JavaScript is the while loop is to execute a statement or
code block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.
Syntax
while(expression)
{
Statement(s) to be executed if expression is true
}

Java Script 27
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 23
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> Output

<!-- var count =0; Starting Loop


Current Count : 0
document.write("Starting Loop "); Current Count : 1
while(count <10){ Current Count : 2
Current Count : 3
document.write("Current Count : "+ count +"<br />"); Current Count : 4
Current Count : 5
count++;
Current Count : 6
} Current Count : 7
Current Count : 8
document.write("Loop stopped!");
Current Count : 9
//--> </script> </body> </html> Loop stopped!

THE DO...WHILE LOOP


The do...while loop is similar to the while loop except that the
condition check happens at the end of the loop. This means that the
loop will always be executed at least once, even if the condition is false.
Syntax
do{ Output
Statement(s) to be executed; Starting Loop
Current Count : 0
}while(expression); Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!

Example – 24
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> <!-- var count =0;
document.write("Starting Loop"+"<br />");
do{
document.write("Current Count : "+ count +"<br />");
count++;
}while(count <5);
document.write("Loop stopped!");
//--> </script> </body> </html>

Java Script 28
Nandha Arts and Science College PHP – I Unit BCA Department

JavaScript - For Loop


The 'for' loop is the most compact form of looping. It includes the following three important parts −
• The loop initialization where we initialize our counter to a starting value. The initialization statement is
executed before the loop begins.
• The test statement which will test if a given condition is true or not. If the condition is true, then the
code given inside the loop will be executed, otherwise the control will come out of the loop.
• The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
FLOW CHART
The flow chart of a for loop in JavaScript would be as follows −
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}

Example – 25
<html> <body> Starting Loop
<script type=“text/JavaScript”> Current Count : 0
Current Count : 1
<!-- var count; Current Count : 2
document.write("Starting Loop"+"<br />"); Current Count : 3
Current Count : 4
for(count =0; count <10; count++){
Current Count : 5
document.write("Current Count : "+ count ); Current Count : 6
document.write("<br />"); Current Count : 7
Current Count : 8
} Current Count : 9
document.write("Loop stopped!"); Loop stopped!
//--> </script> </body> </html>

JavaScript for...in loop


 The for...in statement is used to loop (iterate) through the elements of an array or through the
properties of an object.
 The code in the body of the for ... in loop is executed once for each element/property.
 The variable argument can be a named variable, an array element, or a property of an object.

Java Script 29
Nandha Arts and Science College PHP – I Unit BCA Department

 A for...in loop only iterates over enumerable properties. Objects created from built–in constructors
like Array and Object have inherited non–enumerable properties from Object.prototype and
String.prototype.
 The for loop is very useful when you already know how many times a piece of code should run. In
JavaScript for loop iterates through each and every item in an array. Arrays in JavaScript are zero-
based, that means array’s first item’s index number will be 0 and so on as mentioned below in the
screenshot.

Syntax
for (variable in object)
{
code to be executed
}
Variable : A different property name is assigned to variable on each iteration.
Object : Object whose enumerable properties are iterated. In each iteration, one property from object is assigned to
variable name and this loop continues till all the properties of the object are exhausted .

Javascript forEach method calls a provided function for each and every element in an array.
arrayName.forEach(function(currentValue, index, array), thisValue)
JavaScript forEach() Method – Parameter Values
currentValue is a required argument. It represents the value of the current item in an array.
Index is an optional parameter. It represents the current element in an array.
Array is an optional parameter. This array represents the current element which belongs to the array object.
thisValue this parameter is an optional parameter. It represents the used values when executing the callback
Example
var namesArray = ['Rose', 'Lilly', 'Jasmine', 'Lotus', 'Tulip']; Rose
Lilly
namesArray.forEach(function(data)
Jasmine
{ Lotus
Tulip
console.log(data);
})

Array iteration and for...in


Array indexes are just enumerable properties with integer names and are otherwise identical to general
Object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in
loop statement will return all enumerable properties, including those with non–integer names and those that
are inherited.

Java Script 30
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 26
console object commands
Output
<html>
This table shows the syntax for the
<body> "obj. a = 1"
console object commands that you
<script > “obj. b = 2" can use in the JavaScript Console
window, or that you can use to send
<!-- "obj. c = 3" messages to the console from your
var obj = {a:1, b:2, c:3}; code. This object provides a number
of forms so that you can distinguish
for (var prop in obj) { between informational messages
and error messages, if you want to.
console.log("obj." + prop + " = " + obj[prop]);
You can use the longer command
}
form window.console[command] if
</script> you need to avoid possible
confusion with local objects named
</body> console.
</html>

Example – 27
<html>
<body>
<h2> JavaScript Loops</h2>
<p> The for/in statement loops through the properties of an object.</p>
<p id="demo"> </p>
<script>
var txt = "";
var person = {fname:"Karthick", lname:"Raja, age:25};
JavaScript Loops
var x; The for/in
for (x in person) statement loops
through the
{ properties of an
object.
txt += person[x] + " ";
Karthick Raja 25
}
document.getElementById("demo").innerHTML = txt;
</script> </body> </html>

JAVASCRIPT - LOOP CONTROL


JavaScript provides full control to handle loops and switch statements. There may be a situation when you
need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip
a part of your code block and start the next iteration of the loop.

Java Script 31
Nandha Arts and Science College PHP – I Unit BCA Department

To handle all such situations, JavaScript provides break and continue statements. These statements are used
to immediately come out of any loop or to start the next iteration of any loop respectively.

THE BREAK STATEMENT


The break statement, which was briefly introduced with the switch
statement, is used to exit a loop early, breaking out of the enclosing
curly braces.
Example
The following example illustrates the use of a break statement with a
while loop. Notice how the loop breaks out early once x reaches 5 and
reaches to document.write(..) statement just below to the closing
curly brace −

Example – 28
<html>
<body>
Output
<script type=“text/JavaScript”>
<!--
Entering the loop
var x =1;
2
document.write("Entering the loop<br /> "); 3
while(x <20) 4
{ 5
if(x ==5)
{
break;// breaks out of loop completely
}
x = x +1;
document.write(x+"<br />");
}
document.write("Exiting the loop!<br /> ");
//--> </script> </body> </html>

THE CONTINUE STATEMENT


The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the
remaining code block. When a continue statement is encountered, the program flow moves to the loop check
expression immediately and if the condition remains true, then it starts the next iteration, otherwise the
control comes out of the loop.

Java Script 32
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 29
<html> <body>
<script type=“text/JavaScript”>
Output
<!--var x =1;
Entering the loop
document.write("Entering the loop<br /> ");
2
while(x <10) 3
{ 4
x = x +1; 6
if(x ==5) 7
8
{ continue;
9
} 10
document.write( x+"<br />"); Exiting the loop!
}
document.write("Exiting the loop!<br /> ");
//--> </script> </body> </html>

JAVA SCRIPT FUNCTION:


• A function is a group of reusable code which can be called anywhere in your program you can divide
your big program in a number of small and manageable function.
• A function is a subprogram designed to perform a particular task.
• Functions are executed when they are called invoking a function.
• Values can be passed into functions and used within the function.
• Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.

Parameters vs. Arguments.


If you’re new to JavaScript, you may have heard the terms parameters and arguments used interchangeably.
While very similar, there is an important distinction to make between these two keywords.
Parameters are used when defining a function, they are the names created in the function definition. In fact,
during a function definition, we can pass in up to 255 parameters! Parameters are separated by commas ().
Arguments, on the other hand, are the values the function receives from each parameter when the function
is executed (invoked).
Invoking a Function: Functions execute when the function is called. This process is known as invocation. You
can invoke a function by referencing the function name, followed by an open and closed parenthesis: ().
Function Definition:
• The most common way to define a function in a java script is by using function key words followed by
a unique function name.

Java Script 33
Nandha Arts and Science College PHP – I Unit BCA Department

• A list of parameters (that might-


empty) & a statement block
surrounded by curly braces.
Syntax:
function functionname
(parameters)
{
Statement(s) ; (or)
Function body
}
Function Parameter:
• There is a facility to pass different parameter while calling a function.
• This passed parameter can be captured inside a function and any manipulation can be done over this parameter.

• A function can take multiple parameter separate by comma( , ).

Example – 30
<html> <body>
<script>
function getcube(number){
alert(number * number * number);
} </script> <form>
<input type="button" value="click" onClick="getcube(4)"/>
</form> </body> </html>

Return Statement:
Java Script function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement is a function.
function firstfunction(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = firstfunction ('Sumathi', 'Raja');
document.write (result );
}

Java Script 34
Nandha Arts and Science College PHP – I Unit BCA Department

JAVA SCRIPT EVENTS:


• Java script instruction with html is handled throw event that occurs when the user or browser
manipulates a page.
• When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples
include events like pressing any key, closing a window, resizing a window, etc.
• Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of
response imaginable.
Examples of events are like pressing any key, closing window, resizing window etc.,

onClick: Use this to invoke JavaScript upon clicking (a link, or form boxes)

onload: Use this to invoke JavaScript after the page or an image has finished loading.

onmouseover: Use this to invoke JavaScript if the mouse passes by some link

onmouseout: Use this to invoke JavaScript if the mouse goes pass some link

onunload: Use this to invoke JavaScript right after someone leaves this page.

What can JavaScript Do?


Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
• Things that should be done every time a page loads
• Things that should be done when the page is closed
• Action that should be performed when a user clicks a button
• Content that should be verified when a user inputs data And more ...
Many different methods can be used to let JavaScript work with events:
• HTML event attributes (Features) can execute
JavaScript code directly
• HTML event attributes can call JavaScript
functions
• You can assign your own event handler functions
to HTML elements,

Java Script 35
Nandha Arts and Science College PHP – I Unit BCA Department

On_Click Event Type:


Example – 31
<html>
<head>
<script type="text/JavaScript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onClick= "sayHello()" value="Say Hello"/>
</form>
</body>
</html>
ONSUBMIT EVENT TYPE:
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.
How to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If
validate() function returns true, the form will be submitted, otherwise it will not submit the data.

Example – 32
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>

Java Script 36
Nandha Arts and Science College PHP – I Unit BCA Department

function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>

ONMOUSEOVER AND ONMOUSEOUT


These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when
you move your mouse out from that element.

Example – 33
<html> <head>
<script type="text/JavaScript">
<!--
function popup()
{
alert("Hello World")
} //--> </script> </head>
<body>
<input type="button" value="Click Me!" onClick="popup()"><br />
Hover Me!</a> </body> </html>

Calling a function with arguments:


When you call a function you can pass along some values to it. These values are called arguments or parameters.
This argument can be used inside function you can send many arguments you like separate by comma.
MyFunction (argument1, argument2)
Require the argument as variables, when you declare a function.
function myfunction(var1,var2)
{ Some code; }
The variable and argument must be in the expected order. The first variable is given the value of the
first positive argument etc.,

Java Script 37
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 34
<button onClick = “Myfunction (‘Karthik’,‘Raja’)“> tryit>
</button>
<Script language=”java script” type=”text/java script”>
<!-- function myfunction(fname, lname)
{ alert (“welcome” +fname+ ” “ +lname);
} // -- > </script> Output
Welcome Karthik Raja
Function with a return value:
Syntax:
function funtion name()
{ statements;
return ; }
Something you want your function return a value back to where call was mode this possible by using return statement.

Example – 35 Calculate a product two no:


Output
Function myfunction(a, b)
The Inner html of a demo element will be 12.
{ return a * b;
} document. getIelementbyid(“demo”.inner html myfunction(4,3);
Example – 36
Function MyFunction(a, b)
Output
{
a + b condition is true.
if (a > b)
{
return;
}
x = a + b;
}

HTML 5 STANDARD EVENTS


The standard HTML 5 events are listed here for your reference. Here script indicates a JavaScript function to
be executed against that event.

Java Script 38
Nandha Arts and Science College PHP – I Unit BCA Department

Attribute Value Description


Offline script Triggers when the document goes offline
Onabort script Triggers on an abort event
onafterprint script Triggers after the document is printed
onbeforeonload script Triggers before the document loads
onbeforeprint script Triggers before the document is printed
Onblur script Triggers when the window loses focus
oncanplay script Triggers when media can start play, but might has to stop for buffering
oncanplaythrough script Triggers when media can be played to the end, without stopping for buffering
onchange script Triggers when an element changes
onClick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggered
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when an element is dragged
ondragend script Triggers at the end of a drag operation
ondragenter script Triggers when an element has been dragged to a valid drop target
ondragleave script Triggers when an element is being dragged over a valid drop target
ondragover script Triggers at the start of a drag operation
ondragstart script Triggers at the start of a drag operation
ondrop script Triggers when dragged element is being dropped
ondurationchange script Triggers when the length of the media is changed
onemptied script Triggers when a media resource element suddenly becomes empty.
onended script Triggers when media has reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets user input
onhaschange script Triggers when the document has change
oninput script Triggers when an element gets user input
oninvalid script Triggers when an element is invalid
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and released
onkeyup script Triggers when a key is released
onload script Triggers when the document loads
onloadeddata script Triggers when media data is loaded
onloadedmetadata script Triggers when the duration and other media data of a media element is loaded
onloadstart script Triggers when the browser starts to load the media data
onmessage script Triggers when the message is triggered
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse pointer moves
onmouseout script Triggers when the mouse pointer moves out of an element
onmouseover script Triggers when the mouse pointer moves over an element
onmouseup script Triggers when a mouse button is released
onmousewheel script Triggers when the mouse wheel is being rotated

Java Script 39
Nandha Arts and Science College PHP – I Unit BCA Department

onoffline script Triggers when the document goes offline


onoine script Triggers when the document comes online
ononline script Triggers when the document comes online
onpagehide script Triggers when the window is hidden
onpageshow script Triggers when the window becomes visible
onpause script Triggers when media data is paused
onplay script Triggers when media data is going to start playing
onplaying script Triggers when media data has start playing
onpopstate script Triggers when the window's history changes
onprogress script Triggers when the browser is fetching the media data
onratechange script Triggers when the media data's playing rate has changed
onreadystatechange script Triggers when the ready-state changes
onredo script Triggers when the document performs a redo
onresize script Triggers when the window is resized
onscroll script Triggers when an element's scrollbar is being scrolled
onseeked script Triggers when a media element's seeking attribute is no longer true, and the seeking has ended
onseeking script Triggers when a media element's seeking attribute is true, and the seeking has begun
onselect script Triggers when an element is selected
onstalled script Triggers when there is an error in fetching media data
onstorage script Triggers when a document loads
onsubmit script Triggers when a form is submitted
onsuspend script Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched
ontimeupdate script Triggers when media changes its playing position
onundo script Triggers when a document performs an undo
onunload script Triggers when the user leaves the document
onvolumechange script Triggers when media changes the volume, also when volume is set to "mute"
onwaiting script Triggers when media has stopped playing, but is expected to resume

Java script Arrays


The Array object lets you store multiple
values in a single variable. It stores a fixed-
size sequential collection of elements of
the same type. An array is used to store a
collection of data, but it is often more
useful to think of an array as a collection
of variables of the same type.

Java Script 40
Nandha Arts and Science College PHP – I Unit BCA Department

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax: var array_name = [item1, item2,..];
The Array parameter is a list of strings or integers. When you specify
a single numeric parameter with the Array constructor, you specify
the initial length of the array. The maximum length allowed for an
array is 4,294,967,295.

Example 36
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var cars = ["Benz","Volvo","BMW"];
document.write(cars);
</script>
</body>
</html>

JavaScript Arrays
Benz, Volvo, BMW

Array Properties
Here is a list of the properties of the Array object along with their description.
Property Description
constructor Returns a reference to the array function that created the object.
index The property represents the zero-based index of the match in the string
input This property is only present in arrays created by regular expression matches.
length Reflects the number of elements in an array.
prototype The prototype property allows you to add properties and methods to an object.
JavaScript Class:
A JavaScript class is a type of function. Classes are declared with the class keyword. We can use class
expression syntax to initialize the class.
We can define a class with the following syntax of JavaScript.

Java Script 41
Nandha Arts and Science College PHP – I Unit BCA Department

// Initialising a class definition


Class Hero
{
constructor(name, level)
{
this.name = name;
this.level = level;
}
}
We know that a constructor function is meant to be an object by the capitalization of the first letter. The class
keyword communicates in a straighter forward manner in the objective of our function. The only difference
in the syntax of the initialization is using the class keyword of function and assigning the properties inside a
constructor () method.

JavaScript Objects:
• Objects in JavaScript are its most important data type and forms the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data types (Numbers, String,
Boolean, Null, Undefined, Symbol) in the sense that while these primitive data types all store a single
value each (depending on their types).
• An object is also a reference data type. Variables as a reference value are given a reference or a pointer
to that value. The variables don’t actually store the value.
• Objects in JavaScript may be defined as an unordered collection of related data or primitive or
reference types, in the form of “key: value” pairs. These keys can be variable or functions and are
called Properties and Methods, in the context of an object.
• In JavaScript, almost ‘Everything’ is an object. If defined with “new” keyword.

Example 38
<script>
class User
{ Karthi
constructor(name)
{
this.name = name;
}
sayHi()
{
alert(this.name);
}
}

Java Script 42
Nandha Arts and Science College PHP – I Unit BCA Department

// Usage:
user = new User("Karthi");
user.sayHi();
</script>
You can use object properties 2 ways:
Example
1. Name = person.lastname; 2. Name = person(“lastname”);
Undefined and null
Undefined is value of a variable no value, Variable can be empty by setting value to be null.
Example cars=null;

Declaring variables types:


When you declare a new variables you can declare it type using=”new” keyword.
var x = new string var person = new objects
var z = new Boolean var cars = new array
var y = new number
Properties and methods:
• Properties are value associated with objects.
• Methods are action that objects can performed.
Sample : A real life objects areas:
Properties Methods:
Car name= bmw Car.start()
Car model= 2011 Car.drive()
Car color= red Car.break()
• The properties are including in name, model, weight, color, etc….
• All car has these properties but the property values differ from car to car.
• The method of the car could be start (), drive (), break (), etc….
• All car has these methods but they are performing at different times.
Object in java script:
• The java script objects are variables with properties and methods. var text=” hai ”;
• You actually created a java script string object. The string object has a build-in property called length.
• For the string above length has the value five. The string object also has several builds.

Java Script 43
Nandha Arts and Science College PHP – I Unit BCA Department

Example 38
user = { user = {
name: "JANU", J name: "JANU", h
age: 30, A age: 30, }; e
sayHi() N user.sayHi() = funtion() ll
{ { o
U
alert(this.name); alert(“hello”);
} };
}; user.sayHi();
user.sayHi(); </script>
</script>
JAVA SCRIPT ERRORS & EXCEPTIONS HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors and (c) Logical Errors.

a) SYNTAX ERRORS
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and
at interpret time in JavaScript.
Example the following line causes a syntax error because it is missing a closing parenthesis.
<script language = “JavaScript” type="text/JavaScript">
<!--
window.print();
//--> </script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax
error is affected and the rest of the code in other threads gets executed assuming nothing in them depends
on the code containing the error.

b) RUNTIME ERRORS
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at runtime,
it is trying to call a method that does not exist.
<script language = “JavaScript” type="text/JavaScript">
<!-- window.printme(); //--> </script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.

c) LOGICAL ERRORS
Logic errors can be the most difficult typeof errors to track down. These errors are not the results of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script
and you do not get the results you expected.

Java Script 44
Nandha Arts and Science College PHP – I Unit BCA Department

You cannot catch those errors, because it depends on your business requirement what type of logic you
want to put in your program.

Java script Errors Handling (throw, try, catch).


try: It is used to test block of code for errors.
catch: The catch statement used to handle the errors.
throw: Used to create a custom error.
Error will happen:
• When the java script engine is executing java script code, different error can occur.
• It can be syntax error typically coding error or type made by the programmer.
• It can be misspelled or missing features in language (may be due to browser differences).
• In can be error due to wrong input form a user or internet server & of course it can be many
other unforeseeable things.

Java script throw errors:


• When you error occur when something goes to wrong, when java script engine will normally
stop & generated an error message.
• The technical term for this is color java script will throw an error.
Java script try and catch:
• The try statement allows you to define a block of code to be tested for error while it is being executed.
• The Catch statement allows you to define of code to be executed, if an error occur in try
block. The java script statement try and catch come in parts.
Syntax:
try
{ //run some code here. }
catch (error)
{ //handle the error }
Example – 39 (try..catch)
<html> <head>
<script type="text/JavaScript">
Click the following to see the result:
<!--
function myFunc()
Value of variable a is: 100

Java Script 45
Nandha Arts and Science College PHP – I Unit BCA Department

{
var a = 100;
try {
document.write("Value of variable a is : " + a );
}
catch (e) {
document.write ("Error: " + e.description );
}
} Definition: - The getElementById()
method returns the element that
//--> has the ID attribute with the
</script> specified value. This method is
one of the most common
</head> methods in the HTML DOM, and is
<body> used almost every time you want
to manipulate, or get info from, an
<p>Click the following to see the result:</p> element on your document.
<form> Definition:- The Document Object
<input type="button" value="Click Me" Model (DOM) is a programming
API for HTML and XML
onClick="myFunc();" /> documents. It defines the logical
structure of documents and the
</form>
way a document is accessed and
</body> </html> manipulated.

Here is the try...catch...finally block syntax −


<script type="text/JavaScript">
<!--
try { // Code to run
[ break;]
}
catch ( e ) { // Code to run if an exception occurs
[ break; ]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}] //--> </script>
Throw statement:
• It allows creating a custom error. The correct technical term is to create on throw and exception.
• If you use the throw statement together with the try and catch, you can control program flow and
generate custom error messages.

Java Script 46
Nandha Arts and Science College PHP – I Unit BCA Department

Syntax:
Throw exception
Exception can be java script string, number, Boolean or an objects.

Example – 40
<html>
Click the following to see the result:
<head>
<script type="text/JavaScript">
<!-- Value of variable a is: 100

function myFunc()
{ Finally block will always execute!
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch (e) {
alert("Error: " + description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p> Click the following to see the result:</p>
<form>
<input type= "button" value= "Click Me" onClick= "myFunc();" />
</form>
</body>
</html>

---x---x---x---

Java Script 47
Unit-I

Visual Basic SCRIPT


• VBScript is a client-side scripting language like JavaScript.
• Visual Basic Script is a subset of Visual Basic 4.0 language.
• A scripting language is a lightweight programming language.
• VB Script is the default language in ASP (Active Server Pages).
• VB Script stands forms a subset of Visual Basic for Applications (VBA).
• VB Script can be used to write both client-side and server-side scripting (ASP).
• It was developed by Microsoft to provide more processing power to Web pages.
• VBScript was developed by Microsoft with the intention of developing dynamic web pages.

Features of VBScript
• VBScript is a lightweight scripting language, which has a lightning fast interpreter.
• VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to
implement.
• Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented
Programming language.
• It uses Component Object Model (COM) in order to access the elements of the environment in
which it is executing.
• Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet
Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH)

VBScript – Version History and Uses


VB Script was introduced by Microsoft way back in 1996 and its first version was 1.0. The current
stable version of VBScript is 5.8, which is available as part of IE8 or Windows 7. The VBScript usage
areas are aplenty and not restricted to the below list.
• VBScript is used as a scripting language in one of the popular Automation testing tools – Quick
Test Professional shortened as QTP.
• Windows Scripting Host, which is used mostly by Windows System administrators for
automating the Windows Desktop.
• Active Server Pages (ASP), a server side scripting environment for creating dynamic webpages
which uses VBScript or Java Script.
• VBScript is used for Client side scripting in Microsoft Internet Explorer.
Nandha Arts and Science College PHP – I Unit BCA Department

Disadvantages
• VBScript is used only by IE Browsers. Other browsers such as Chrome, Firefox don’t Support
VBScript.
• VBScript has a Limited command line support.
• Since there is no development environment available by default, debugging is difficult.

Where VBScript is today?


The current version of VBScript is 5.8, and with the recent development of .NET framework, Microsoft
has decided to provide future support of VBScript within ASP.NET for web development. Hence, there
will NOT be any newer versions of VBScript engine but the entire defect fixes and security issues are
being addressed by the Microsoft sustaining Engineering Team. However, VBScript engine would be
shipped as part of all Microsoft Windows and IIS by default.

Example – 41
<html> My First
<body> VBScript Program
<script language="vbscript"
type="text/vbscript">
document.write("My First VBScript Program")
</script>
</body>
</html>

Whitespace and Line Breaks


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

Formatting
VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as
semicolon is used to terminate a particular statement.

Single Line Syntax


Colons are used when two or more lines of VBScript ought to be written in a single line. Hence, in
VBScript, Colons act as a line separator.
<script language = "vbscript" type="text/vbscript">
var1 = 10, var2 = 20
</script>

VB Script
49
Nandha Arts and Science College PHP – I Unit BCA Department

Multiple Line Syntax


When a statement in VBScript is lengthy and if user wishes to break it into multiple lines, then the
user has to use underscore "_". This improves the readability of the code. The following example
illustrates how to work with multiple lines.
The Sum of 2
Example – 42 numbers 30
<script language ="vbscript" type="text/vbscript">
dim n1 = 10, n2 = 20;
Sum = n1 + n2;
document.write("The Sum of 2 numbers" & Sum);
</script>

RESERVED WORDS
And Eqv LSet Resume
As Erase Me RSet
Boolean Eval Mod Select
ByRef Event Msgbox SendKeys
Byte Execute New Set
ByVal ExecuteGlobal Next Shared
Call Exit Not Single
Case FALSE Nothing Static
Class For Null Stop
Const Function On Sub
Currency Get Option Then
Debug GoTo Option Explicit To
Dim If Optional TRUE
Do Imp Or Type
Double Implements ParamArray TypeOf
Each In Preserve Until
Else Integer Private Variant
ElseIf Is Public Wend
Empty Let RaiseEvent While
End Like Randomize With
EndIf Long ReDim Xor
Enum Loop Rem

CASE SENSITIVITY
VBScript is a case-insensitive language. This means that language keywords, variables, function names
and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers
int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.

VB Script
50
Nandha Arts and Science College PHP – I Unit BCA Department

COMMENTS IN VBSCRIPT
Comments are used to document the program logic and the user information with which other
programmers can seamlessly work on the same code in future. It can include information such as
developed by, modified by and it can also include incorporated logic. Comments are ignored by the
interpreter while execution. Comments in VBScript are denoted by two methods.
Any statement that starts with a Single Quote (‘) is treated as comment. Following is the example:
<script language="vbscript" type="text/vbscript">
<!--
' This Script is invoked after successful login
' Written by : karthik
' Return Value : True / False
//-- > </script>
Any statement that starts with the keyword “REM”. Following is the example:
<script language="vbscript" type="text/vbscript">
<!--
REM This Script is written to Validate the Entered Input
//-- > </script>

Enabling VB Script in Browsers


Not all the modern browsers support VBScript. VBScript is supported just by Microsoft's Internet
Explorer while other browsers (Firefox and Chrome) support just JavaScript. Hence, developers
normally prefer JavaScript over VBScript.
Though Internet Explorer (IE) supports VBScript, you may need to enable or disable this feature
manually. This tutorial will make you aware of the procedure of enabling and disabling VBScript
support in Internet Explorer.

VBScript in Internet Explorer


Here are simple steps to turn on or turn off VBScript in your Internet Explorer:
 Follow Tools -> Internet Options from the menu  Scroll down till you find Scripting option
 Select Security tab from the dialog box  Select Enable radio button under Active scripting
 Click the Custom Level button  Finally click OK and come out
To disable VBScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

VBScript Placement in HTML File


There is a flexibility given to include VBScript code anywhere in an HTML document.
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.

VB Script
51
Nandha Arts and Science College PHP – I Unit BCA Department

VBScript in <head>...</head> section


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

Example – 43
<html> <head>
<script type="text/Vbscript">
<!--
function sayHello()
Msgbox("Hello World")
End Function
//--> </script> </head>
<body>
<input type="button" onClick= "sayHello()" value= "Say Hello" />
</body> </html>

VBScript in <body>...</body> section VBScript Body


If you need a script to run as the page loads so that the script generates content
in the page, the script goes in the <body> portion of the document. In this case, Section

you would not have any function defined using VBScript: This is web page

Example – 44
<html>
<body>
<script type="text/vbscript">
<!
document.write("VBScript Body Section")
//-->
</script>
<p> This is web page </p>
</body> </html>

VBScript in <body> and <head> Sections


Example – 45
<html> <head>
<script type="text/vbscript">
<!--

VB Script
52
Nandha Arts and Science College PHP – I Unit BCA Department

Function sayHello()
msgbox("Hello World")
End Function
//-->
</script> </head> <body>
<script type="text/vbscript">
<!-- document.write("Hello World")
//-->
</script>
<input type="button" onClick="sayHello()" value="Say Hello" />
</body> </html>

VBScript in External File


As you begin to work more extensively with VBScript, you will likely find that there are cases, where you
are reusing identical VBScript code on multiple pages of a site. You are not restricted to be maintaining
identical code in multiple HTML files. The script tag provides a mechanism to allow you to store VBScript in
an external file and then include it into your HTML files. Here is an example to show how you can include
an external VBScript file in your HTML code using script tag and its src attribute:

Example – 46
<html> <head>
<script language = “Javascript” type="text/vbscript" src="filename.vbs">
</script> </head>
<body> ....... </body> </html>
To use VBScript from an external file source, you need to write your all VBScript source code in a
simple text file with extension ".vbs" and then include that file as shown above. For Eg:-, you can keep
the following content in filename.vbs file and then you can use sayHello function in your HTML file
after including filename.vbs file.
Function sayHello()
Msgbox "Hello World"
End Function

VBScript Placement in QTP


VBScript is placed in QTP (Quick Test Professional) tool but it is NOT enclosed within HTML Tags. The
Script File is saved with the extension .vbs and it is executed by QTP execution engine.

VBScript Variables
A variable is a named memory location used to hold a value that can be changed during the script
execution. VBScript has only one fundamental data type, Variant.

VB Script
53
Nandha Arts and Science College PHP – I Unit BCA Department

Rules for Declaring Variables


 Variable name must begin with an alphabet.
 Variable names cannot exceed 255 characters.
 Variables should not contain a period (.)
 Variable names should be unique in the declared context.
Declaring Variables
Variables are declared using “dim” keyword. Since there is only one fundamental data type, all the
declared variables are variant by default. Hence, a user need not mention the type of data during
declaration.
Example 1: In this Example, in Value can be used as a String, Integer or even arrays. Dim Var
Example 2: Two or more declarations are separated by comma(,) Dim Var1, Var2
Assigning Values to the Variables
Values are assigned similar to an algebraic expression. The variable name on the left hand side
followed by an equal to (=) symbol and then its value on the right hand side.
Rules
• The numeric values should be declared without double quotes.
• The String values should be enclosed within double quotes(")
• Date and Time variables should be enclosed within hash symbol(#)
Samples
Value1 = 25
Strvalue = “VBScript”
Date1 = #01/01/2020#
Time1 = #12:30:44 PM#
Scope of the Variables
Variables can be declared using the following statements that determines the scope of the variable.
The scope of the variable plays a crucial role when used within a procedure or classes.
• Dim
• Public
• Private

Dim
Variables declared using “Dim” keyword at a Procedure level are available only within the same
procedure. Variables declared using “Dim” Keyword at script level are available to all the procedures
within the same script.
Example: In the below example, the value of Var1 and Var2 are declared at script level while Var3 is declared
at procedure level.

VB Script
54
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 47
<html>
<body>
<script language="vbscript" 25 15
type="text/vbscript">
<!--
Dim Var1, Var2
Call add()
Function add()
10
Var1 = 10
Var2 = 15
Dim Var3
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level

Msgbox Var2 ' Displays 15 as Var2 is declared at Script level

Msgbox Var3 ' Var3 has No Scope outside the procedure. Prints Empty

//-->
</script>
</body>
</html>

Public
Variables declared using "Public" Keyword are available to all the procedures across all the associated scripts.
When declaring a variable of type "public", Dim keyword is replaced by "Public".
Example: Var1 and Var2 are available at script level while Var3 is available across the associated scripts and
procedures as it is declared as Public.

Example – 48
<html>
<head> <title> Variables declared using public </title> </head>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim Var1, Var2
Public Var3
Call add()

VB Script
55
Nandha Arts and Science College PHP – I Unit BCA Department

Function add()
Var1 = 100
Var2 = 150
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 100 as Var1 is declared at Script level
Msgbox Var2 ' Displays 150 as Var2 is declared at Script level
Msgbox Var3 ' Displays 250 as Var3 is declared as Public
//-->
</script> Var1
Var3
</body>
</html> 250 100

Var2 Var3

150 250

Private
Variables that are declared as "Private" have scope only within that script in which they are declared.
When declaring a variable of type "Private", Dim keyword is replaced by "Private".

Example – 49
Var1 and Var2 are available at Script Level. Var3 is declared as Private and it is available only for this particular script. Use
of "Private" Variables is more pronounced within the Class.
<html>
<head>
<title> Variables that are declared as "Private" </title>
</head>
<body>
<script language="vbscript" type="text/vbscript">
Dim Var1, Var2
Private Var3
Call add()

VB Script
56
Nandha Arts and Science College PHP – I Unit BCA Department

Function add()
Var1 = 1000
Var2 = 1500
Var3 = Var1+Var2
Msgbox Var3 'Displays the sum of two values.
End Function
Msgbox Var1 ' Displays 1000 as Var1 is declared at Script level
Msgbox Var2 ' Displays 1500 as Var2 is declared at Script level
Msgbox Var3 ' Displays 2500 but Var3 is available only for this script.
</script>
</body> Var3 Var1
</html>
2500 1000

Var3

Var2

1500 2500

Constant is a named memory location used to hold a value that CANNOT be changed during the
script execution. If a user tries to change a Constant Value, the Script execution ends up with an
error. Constants are declared the same way the variables are declared.

Declaring Constants
Syntax : [Public | Private] Const Constant_Name = Value
The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public
constants are available for all the scripts and procedures while the Private Constants are available
within the procedure or class. One can assign any value such as number, String or Date to the declared
Constant.

Example – 50
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--

VB Script
57
Nandha Arts and Science College PHP – I Unit BCA Department

Dim intRadius intRadius = 20


const pi=3.14
Area = pi*intRadius*intRadius
1256
Msgbox Area
//-->
</script>
</body>
</html>

Example – 51
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Const myString = "VBScript"
Const myDate = #01/01/2050#
Msgbox myString VBScript 01-01-2050
Msgbox myDate
//-->
</script>
</body> </html>

What is an Operator?
Let’s take an expression 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called the
operator. VBScript language supports following types of operators:
• Arithmetic Operators • Logical (or Relational) Operators
• Comparison Operators • Concatenation Operators

The Arithmetic Operators Assume A= 5 and B=10

Operator Description Example


+ Adds two operands A + B will give 15
- Subtracts second operand from the first A - B will give -5
* Multiply both operands A * B will give 50
/ Divide numerator by denominator B / A will give 2
% Modulus Operator and remainder of after an integer division B MOD A will give 0
^ Exponentiation Operator B ^ A will give 100000

VB Script
58
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 52
<html> <body> <script language="vbscript" type="text/vbscript">
<!--
dim a = 5, b = 10, c;
c = a+b
Result
document.write ("Addition Result is " &c)
document.write (“<br>“) Addition Result is 15
c = a-b Subtraction Result is -5

document.write ("Subtraction Result is " &c) Multiplication Result is 50


Division Result is 2
document.write (“<br>“)
Modulus Result is 0
c = a*b Exponentiation Result is 100000
document.write ("Multiplication Result is " &c)
document.write ("<br>")
c = b/a
document.write ("Division Result is " &c)
document.write ("<br>")
c = b MOD a
document.write ("Modulus Result is " &c)
document.write ("<br>")
c = b^a
document.write ("Exponentiation Result is " &c)
document.write ("<br>")
//--> </script> </body> </html>

The Comparison Operators Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


Checks if the value of two operands are equal or not, if yes
== (A == B) is False.
then condition becomes true.
Checks if the value of two operands are equal or not, if values
<> (A <> B) is True.
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of
> (A > B) is False.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of
< (A < B) is True.
right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to
>= (A >= B) is False.
the value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the
<= (A <= B) is True.
value of right operand, if yes then condition becomes true.

VB Script
59
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 53
<html> <body>
<script language="vbscript" type="text/vbscript">
<!--
dim a,b,c; a = 10,b = 20,c;
If a=b Then
document.write ("Operator Line 1 : True")
else
document.write ("Operator Line 1 : False") Operator Line 1 : False

end if Operator Line 2 : True

If a<>b Then Operator Line 3 : False

document.write ("Operator Line 2 : True") Operator Line 4 : True

else Operator Line 5 : False


document.write ("Operator Line 2 : False") Operator Line 6 : True
end If
If a>b Then
document.write ("Operator Line 3 : True")
else
document.write ("Operator Line 3 : False")
end If
If a<b Then
document.write ("Operator Line 4 : True")
else
document.write ("Operator Line 4 : False")
end If
If a>=b Then
document.wrte ("Operator Line 5 : True")
Else
document.write ("Operator Line 5 : False")
End If
If a<=b Then
document.write ("Operator Line 6 : True")
else
document.write ("Operator Line 6 : False")
End If
//-->
</script> </body> </html>

VB Script
60
Nandha Arts and Science College PHP – I Unit BCA Department

The Logical Operators Assume variable A holds 10 and variable B holds 0, then:

Operator Description Example


Called Logical AND operator. If both the conditions are a<>0 AND b<>0
AND
True then Expression becomes true.
is False.
OR Called Logical OR Operator. If any of the two conditions are True a<>0 or b<>0
then condition becomes true.
is true.
Called Logical NOT Operator. Use to reverses the logical state of its NOT (a<>0 or b<>0)
NOT
operand. If a condition is true then Logical NOT operator will make false.
is false.
Called Logical Exclusion. It is the combination of NOT and OR Operator. If (a<>0 XOR b<>0)
XOR
one, and only one, of the expressions evaluates to True, result is True.
is false.
Example – 54
<html> <body> <script language="vbscript" type="text/vbscript">
<!-- dim a, b,c ;
a = 10, b = 0, c;
If a<>0 and b<>0 Then
document.write ("AND Operator Result is : True")
Else
document.write ("AND Operator Result is : False")
End If
If a<>0 OR b<>0 Then
document.write ("OR Operator Result is : True")
Else
document.write ("OR Operator Result is : False")
End If
If not(a<>0 OR b<>0) Then
document.write ("NOT Operator Result is : True")
Else
document.write ("NOT Operator Result is : False")
End If
If (a<>0 XOR b<>0) Then
document.write ("XOR Operator Result is : True")
Else
document.write ("XOR Operator Result is : False")
End If
//--> </script> </body> </html>

VB Script
61
Nandha Arts and Science College PHP – I Unit BCA Department

The Concatenation Operators Assume variable A holds 5 and variable B holds 10 then:

Operator Description Example


+ Adds two Values as variable values are Numeric A + B will give 15
& Concatenates two Values A & B will give 510
Example – 55
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a = 5, b = 10,c
Dim a1 = "Microsoft", b1 = "VBScript" c1;
c= a+b
document.write ("Concatenated value:1 is " &c) 'Numeric addition
c= a&b
document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers
c1= a1+b1
document.write ("Concatenated value:3 is " &c1) 'Concatenate two strings
//-->
</script>
</body>
</html> Concatenated value:1 is 15
Concatenated value:2 is 510
Concatenated value:3 is MicrosoftVBScript

VBScript provides the following types of decision making statements.


Statement Description
if statement An if statement consists of a Boolean expression followed by one or more statements.

if..else statement An if else statement consists of a Boolean expression followed by one or more
statements. If the condition is True, the statements under the If statements are

if...elseif..else executed.
An If the condition
if statement is false,
followed by one orthen theElseIf
more Else part of the script
Statements, that isconsists
Executedof Boolean

statement expressions and then followed by an optional else statement, which executes when

nested if statements all the


An if orcondition becomesinside
elseif statement false.another if or elseif statement(s).

switch statement A switch statement allows a variable to be tested for equality against a list of values.

VB Script
62
Nandha Arts and Science College PHP – I Unit BCA Department

If Statements
An If statement consists of a Boolean expression followed by one or more statements. If the
condition is said to be True, the statements under If condition(s) are Executed. If the Condition is
said to be False, the statements after the If loop are executed.
Syntax The syntax of an If statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
Statement n
End If

Example – 56
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
dim a = 11,b = 10;
if a > b Then
document.write ("A is Greater than B" );
end If
//-->
</script> a is Greater than B

</body>
</html>

If…Else Statements
An If statement consists of a Boolean expression followed by one or more statements. If the
condition is said to be True, the statements under If condition(s) are Executed. If the Condition is
said to be False, the statements under Else Part would be executed.

Syntax The syntax of an if…else statement in VBScript is:


If(boolean_expression) Then
Statement 1
.......... Statement n
Else
Statement 1
......... Statement n
End If

VB Script
63
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 57
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim a ; a = 5
Dim b ; b = 25
If a > b Then
b is Greater
document.write("a is Greater")
Else
document.write ("b is Greater")
End If
//-->
</script>
</body>
</html>

If.. ElseIf.. Else Statements


An If statement followed by one or more ElseIf Statements that consists of boolean expressions and
then followed by a default else statement, which executes when all the condition becomes false.
Syntax
The syntax of an If-ElseIf-Else statement in VBScript is:

If(boolean_expression) Then
Statement 1
..... ..... Statement n
ElseIf (boolean_expression) Then
Statement 1
......... Statement n
ElseIf (boolean_expression) Then
Statement 1
......... Statement n
Else
Statement 1
......... Statement n
End If

VB Script
64
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 58
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a a is a NEGATIVE Number
a = -5
If a > 0 Then
document.write (“a is a POSITIVE Number")
ElseIf a < 0 Then
document.write (“a is a NEGATIVE Number")
Else
document.write (“a is EQUAL than ZERO"
End If
//--> </script> </body> </html>

Nested If Statement
If or ElseIf statement inside another If or ElseIf statement(s). The Inner If statements are executed based on
the Outermost If statements. This enables VBScript to handle complex conditions with ease.

Syntax The syntax of a Nested if statement in VBScript is:


If(boolean_expression) Then
Statement 1
.......... Statement n
If(boolean_expression) Then
Statement 1
.......... Statement n
ElseIf (boolean_expression) Then
Statement 1
......... Statement n
Else
Statement 1
......... Statement n
End If
Else
Statement 1
.........
Statement n
End If The Number is a POSITIVE Number
The Number is NOT 0,1,2 or 3
VB Script
65
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 59
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
dim a = 5;
if a > 0 Then
document.write (“The Number is a POSITIVE Number")
if a = 1 Then
document.write (“The Number is Neither Prime NOR Composite")
elseif a = 2 Then
document.write (“The Number is the Only Even Prime Number")
elseif a = 3 Then
document.write (“The Number is the Least Odd Prime Number")
else
document.write (“The Number is NOT 0,1,2 or 3")
end If
elseIf a < 0 Then
document.write (“The Number is a NEGATIVE Number")
else
document.write (“The Number is ZERO")
end If
//--> </script> </body> </html>

Switch Statements
When a user wants to execute a group of statements depending upon a value of an expression, then
he can use Switch Case statements. Each value is called a Case, and the variable being switched ON
based on each case. Case Else statement is executed if test expression doesn't match any of the
Case specified by the user.
Case Else is an optional statement within Select Case, however, it is a good programming practice
to always have a Case Else statement.

VB Script
66
Nandha Arts and Science College PHP – I Unit BCA Department

Syntax
Select Case expression
Case expression list 1
statement1
statement2
........ statement n
Case expression list 2
statement1
statement2
........ statement n
Case expression list n
statement1
statement2
........ statement n
.... Case Else
Else
statement1
else
statement2
....
.... End Select
Example – 60
<html> <body> <script language="vbscript" type="text/vbscript">
<!-- The Number is the Least
dim MyVar = 100
Composite Number
Select case MyVar
case 1
document.write("The Number is the Least Composite Number")
case 2
document.write("The Number is the only Even Prime Number")

case 3
document.write("The Number is the Least Odd Prime Number")
case else
document.write ("Unknown Number")
End select
//-->
</script>
</body> </html>

VB Script
67
Nandha Arts and Science College PHP – I Unit BCA Department

VBScript provides the following types of loops to handle looping requirements.


Description
for loop Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
for ..each loop It is executed if there is at least one element in group and reiterated for each
element in a group.
while..wend loop It tests the condition before executing the loop body.
do..while loops The do..While statements will be executed as long as condition is True.(i.e.,) The
Loop should be repeated till the condition is False.
do..until loops The do..Until statements will be executed as long as condition is False.(i.e.,) The
Loop should be repeated till the condition is True.
For Loops
A for loop is a repetition control structure that allows a developer to efficiently write a loop that
needs to execute a specific number of times.

Syntax The syntax of a for loop in VBScript is:


For counter = start to end [Step step count]
[statement 1]
[statement 2]
.... [statement n]
[Exit For]
[statement 11]
[statement 22]
.... [statement n]
Next
Here is the flow of control in a For Loop:
• The For step is executed first. This step allows you to initialize any loop control variables and
increment the step counter variable.
• Secondly, the condition is evaluated. If it is true, the body of the loop is executed.
• If it is false, the body of the loop does not execute and flow of control jumps to the next
statement just after the For Loop.
• After the body of the for loop executes, the flow of control jumps to the Next statement. This
statement allows you to update any loop control variables. It is updated based on the step
counter value.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the For Loop terminates.

VB Script
68
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 61
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!-- dim a : a=15
for i=0 to a Step 3
document.write("The value is i is : " & i)
The value is i is : 0
document.write(“<br>“) The value is i is : 3
The value is i is : 6
next The value is i is : 9
The value is i is : 12
//--> The value is i is : 15
</script> </body> </html>

For...Each Loops
A For Each loop is used when we want to execute a statement or a group of statements for each element in an
array or collection. A For Each loop is similar to For Loop; however, the loop is executed for each element in an
array or group. Hence, the step counter won't exist in this type of loop and it is mostly used with arrays or used
in context of File system objects in order to operate recursively.

Syntax The syntax of a for Each loop in VBScript is:


For Each element In Group
[statement 1]
[statement 2]
....
[statement n] [Exit For]
[statement 11]
apple
[statement 22]
orange
Next
Mango
Example – 62
<html> <body> <script language="vbscript" type="text/vbscript">
<!-- Dim fruitnames
fruits = Array("apple", "orange", "Mango")
For each item in fruits
fruitnames = fruitnames & item & vbnewline
Next
msgbox fruitnames
</script>
</body> </html>

VB Script
69
Nandha Arts and Science College PHP – I Unit BCA Department

While...Wend Loop
In a While.. Wend loop, if the condition is True, all statements are
executed until Wend keyword is encountered. If the condition is false,
the loop is exited and the control jumps to very next statement after
Wend keyword.

Syntax The syntax of a While..Wend loop in VBScript is:


While condition(s) [statements 1] [statements 2]
...
[statements n] Wend

Example – 63
<html>
<body>
<script type="text/vbscript">
<!--
Dim Counter = 10
While Counter < 15 ' Test value of Counter.
The Current Value: 11
Counter = Counter + 1 ' Increment Counter. The Current Value: 12

document.write("The Current Value: " & Counter) The Current Value: 13


The Current Value: 14
document.write("<br>")
The Current Value: 15
Wend ' While loop exits if Counter Value becomes 15.

//--> </script> </body> </html>

Do..While statement
Do..While loop is used when we want to repeat a set of
statements as long as the condition is true. The Condition may be
checked at the beginning of the loop or at the end of the loop.
Syntax The syntax of a Do..While loop in VBScript is:
Do While condition
[statement 1]
[statement 2]
...
[statement n] [Exit Do]
[statement 1]
[statement 2]
...
[statement n] Loop

VB Script
70
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 64
Do..while loop to check the condition at the beginning of the loop. The statements inside the loop
are executed only if the condition becomes True.
<html> <body>
<script language="vbscript" type="text/vbscript">
<!--
The value of i is : 1
Do While i < 5 i = i + 1 The value of i is : 2

document.write("The value of i is : " & i) The value of i is : 3


The value of i is : 4
document.write("<br>") The value of i is : 5
Loop
//--> </script> </body> </html>

Alternate Syntax
There is an alternate Syntax for Do..while loop which checks the condition at the end of the loop. The
Major difference between these two syntax is explained below with an example.
Do
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop While condition
Example – 65
<html> <body> <script language="vbscript"
type="text/vbscript">
<!--
i=10
do{ The value of i is : 11

i = i + 1
document.write("The value of i is : " & i)
document.write("<br>")
loop While i<3 'Condition is false.

//--> </script> </body> </html>

VB Script
71
Nandha Arts and Science College PHP – I Unit BCA Department

Do... Until Loops


A Do..Until loop is used when we want to repeat a set of
statements as long as the condition is false. The Condition
may be checked at the beginning of the loop or at the end of
loop.

Syntax
The syntax of a Do..Until loop in VBScript is:
Do Until condition [statement 1]
[statement 2]
...
[statement n] [Exit Do] [statement 1]
[statement 2]
...
[statement n] Loop

Example – 66
The following example uses Do..Until loop to check the condition at the beginning of the loop. The
Statements inside the loop are executed only if the condition is false. It exits out of the loop when
the condition becomes true.
<html>
The value of i is : 11
<body> The value of i is : 12

<script language="vbscript" The value of i is : 13


The value of i is : 14
type="text/vbscript"> The value of i is : 15
<!-- The value of i is : 16

i=10
Do Until i>15 'Condition is False. Hence loop will be executed

i = i + 1
document.write("The value of i is : " & i)
document.write("<br>")
Loop
//-->
</script>
</body>
</html>

VB Script
72
Nandha Arts and Science College PHP – I Unit BCA Department

Alternate Syntax There is an alternate Syntax for Do..Until


loop which checks the condition at the end of the loop. The Major
difference between these two syntax is explained below .
do
[statement 1]
[statement 2]
...
[statement n]
[exit Do]
[statement 1]
[statement 2]
...
[statement n]
loop Until condition

Example – 67 Do..Until loop to check the condition at the end of the loop. The Statements inside the

loop are executed at least once even if the condition is True.


<html> <body> <script language="vbscript" type="text/vbscript">
<!--
i=10
The value of i is : 11
Do
i = i + 1
document.write("The value of i is : " & i)
document.write("<br>")
Loop Until i<15 'Condition is True. Hence loop is executed once.
//-->
</script> </body> </html>

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all the remaining statements in the loop are NOT executed. VBScript supports the following
control statements. Click the following links to check their detail.
Control Statement Description
Exit For statement Terminates the For loop statement and transfers execution to the statement
immediately following the loop
Exit Do statement Terminates the Do While statement and transfers execution to the statement
immediately following the loop

VB Script
73
Nandha Arts and Science College PHP – I Unit BCA Department

Exit For statement


An Exit For Statement is used when we want to Exit the For
Loop based on certain criteria. When Exit For is executed, the
control jumps to next statement immediately after the For
Loop.

Syntax
The syntax for Exit For Statement in VBScript is:
Exit For

Example – 68
The following example uses Exit For. If the value of the
Counter reaches 4, the For Loop is Exited and control jumps to
the next statement immediately after the For Loop.

<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
The value is i is : 0
Dim a ; The value is i is : 2
a=10 The value is i is : 4

For i=0 to a Step 2 The value is i is : 40

document.write("The value is i is : " & i)


document.write(“<br>“)
If i=4 Then
i=i*10 'This is executed only if i=4
document.write("The value is i is : " & i)
Exit For 'Exited when i=4
End If
Next
//--> </script> </body> </html>

Exit Do statement
An Exit Do Statement is used when we want to Exit the Do Loops based on certain criteria. It can be
used within both Do..While and Do..Until Loops.
When Exit Do is executed, the control jumps to next statement immediately after the Do Loop.

VB Script
74
Nandha Arts and Science College PHP – I Unit BCA Department

Syntax
The syntax for Exit Do Statement in VBS is: Exit Do

Example – 69
The following example uses Exit Do. If the value of the Counter reaches
10, the Do Loop is Exited and control jumps to the next statement
immediately after the For Loop.
<html>
<body>
<script language="vbscript"
type="text/vbscript">
<!--
i = 0
Do While i <= 100
If i > 10 Then
Exit Do ' Loop Exits if i>10
The Value of i is : 0
End If The Value of i is : 2
document.write("The Value of i is : " &i) The Value of i is : 4
document.write("<br>") The Value of i is : 6
The Value of i is : 8
i = i + 2
The Value of i is : 10
Loop
//-->
</script> </body> </html>

VBScript Procedures
We have two kinds of procedures: The Sub procedure and the Function procedure.
i) Sub procedure:
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that
perform actions but don't return a value. A Sub procedure can take arguments (constants, variables,
or expressions that are passed by a calling procedure).
The following Sub procedure uses two basic, or built-in, VBScript functions, MsgBox and InputBox, to
prompt a user for information. It then displays the results of a calculation based on that information.
The calculation is performed in a Function procedure created using VBScript.
• is a series of statements, enclosed by the Sub and End Sub statements
• can perform actions, but does not return a value
• can take arguments that are passed to it by a calling procedure
• without arguments, must include an empty set of parentheses ()

VB Script
75
Nandha Arts and Science College PHP – I Unit BCA Department

Sub mysub()
some statements
End Sub (or)
Sub mysub(argument1,argument2)
some statements
End Sub
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a
value indicating which button the user clicked.
Syntax MsgBox(prompt[, buttons][, title][, helpfile, context])
InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and
returns the contents of the text box.
Syntax InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
ii) Function procedure:
A Function procedure is a series of VBScript statements enclosed by the Function and End Function
statements. A Function procedure is similar to a Sub procedure, but can also return a value. A
Function procedure can take arguments (constants, variables, or expressions that are passed to it by
a calling procedure). If a Function procedure has no arguments, its Function statement must include
an empty set of parentheses. A Function returns a value by assigning a value to its name in one or
more statements of the procedure. The return type of a Function is always a Variant.
 is a series of statements, enclosed by the Function and End Function statements
 can perform actions and can return a value
 can take arguments that are passed to it by a calling procedure
 without arguments, must include an empty set of parentheses ()
 returns a value by assigning a value to its name
Function myfunction() Function myfunction(argument1,argument2)

some statements (Or) some statements


myfunction=some value myfunction=some value
End Function End Function

Arguments in Procedures
There are two types of arguments in procedures
1) By Val: Indicates that the argument is passed by value.
2) By Ref: Indicates that the argument is passed by reference. By default all arguments are 'ByRef'.

VB Script
76
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 70
Function demo_add(a,b)
demo_add=a+b
End Function
Here ‘a,b’ are the arguments. By default these are 'ByRef'.
In simple terms ‘ByRef’ Means the value which is assigned to the variable with in the function is
permanent and we can use that value out side that function as well.
‘ByVal’ means the value, which is assigned to the variable with in the function, is temporary and we
can use that value only with in that function.

Example – 71
function demo_parameters(byref x,byval y)
x=20 y=50
demo_parameters=x+y
End Function
a=10 b=20
msgbox demo_parameters(a,b)
msgbox a
msgbox b
In the above function ‘x’ and ‘y’ are the arguments, declared as ‘byref’ and ‘byval’. Within that
function we have assigned values to ‘x’ and ‘y’. Outside of the function we have assigned values to
two variables and passing those variables in to the function. Here 'a' is passing reference to x and b
is passing value to y. Within that function we are changing the value for ‘x’. This value is permanent
for 'a' - because 'a' is passed as 'ByRef'. But the value of 'b' will not be changed because it is passed
as 'ByVal'.

What is an Event?
VBScript's interaction with HTML is handled through events that occur when the user or browser
manipulates a page. When the page loads, that is an event. When the user clicks a button, that click
too is an event. Other examples of events include pressing any key, closing window, resizing
window, etc. Developers can use these events to execute VBScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable to occur. Events are a part of the Document Object Model (DOM)
and every HTML element has a certain set of events, which can trigger VBScript Code.

onClick Event Type


This is the most frequently used event type, which occurs when a user clicks mouse's left button. You
can put your validation, warning, etc., against this event type.

VB Script
77
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 72
<html> <head>
<script language="vbscript" type="text/vbscript">
<!--
function sayHello()
msgbox "VBScript Events"
end function
//--> </script> </head> <body>
<input type="button" onClick="sayHello()" value="Say Hello"/>
</body> </html>

onsubmit Event Type


Another most important event type is onsubmit. This event occurs when you try to submit a form.
So you can put your form validation against this event type. The Form is submitted by clicking on
Submit button, the message box appears.

Example – 73
<html> <body>
<script language="VBScript">
<!--
Function fnSubmit()
Msgbox("Hello Welcome to Nandha Arts ")
End Function
//-->
</script>
<form action="/cgi-bin/test.cgi" method="post"
name="form1"onSubmit="fnSubmit()">
<input name="txt1" type="text"><br>
<input name="btnButton1" type="submit" value="Submit">
</form> //--> </script> </body> </html>

onmouseover and onmouseout


These two event types will help you to create nice effects with images or even with text as well. The
onmouseover event occurs when you bring your mouse over any element and the onmouseout
occurs when you take your mouse out from that element.

VB Script
78
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 74
<html> <body> <script language="VBScript">
<!--
function AlertMsg()
Msgbox("ALERT !")
End Function
Function onmouse_over()
Msgbox("Onmouse Over")
End Function
Sub txt2_OnMouseOut()
Msgbox("Onmouse Out !!!")
End Sub
Sub btnButton_OnMouseOut()
Msgbox("onmouse out on Button !")
End Sub
//--> </script>
<form action="page.cgi" method="post" name="form1">
<input name="txt1" type="text" OnMouseOut="AlertMsg()"><br>
<input name="txt2" type="text" OnMouseOver="onmourse_over()">
<input name="Button" type="button" value="Submit">
</form> </body> </html>

ALERT Onmouse Over Onmouse Out onmouse out


on Button

HTML 4 Standard Events


The standard HTML 4 events are listed here for your reference. Here, script indicates a
VBScript function to be executed against that event.
Event Value Description
Onchange script Script runs when the element changes
Onsubmit script Script runs when the form is submitted
Onreset script Script runs when the form is reset
Onblur script Script runs when the element loses focus
Onfocus script Script runs when the element gets focus
Onkeydown script Script runs when key is pressed
Onkeypress script Script runs when key is pressed and released

VB Script
79
Nandha Arts and Science College PHP – I Unit BCA Department

Onkeyup script Script runs when key is released


OnClick script Script runs when a mouse click
Ondblclick script Script runs when a mouse double-click
onmousedown script Script runs when mouse button is pressed
onmousemove script Script runs when mouse pointer moves
Onmouseout script Script runs when mouse pointer moves out of an element
Onmouseover script Script runs when mouse pointer moves over an element
Onmouseup script Script runs when mouse button is released
What is a Class?
In its simplest form, Class can be defined as a blueprint or a template or a category of things having
some attributes in common. An Object is an instance of a Class.
Examples:
If we consider Mobile Phone as a class, its objects can be an iPhone 7, Samsung Galaxy S8 or a
Google Pixel. If we consider Shape as a class, its objects can be a circle, a rectangle or a square.

VB Script
80
Nandha Arts and Science College PHP – I Unit BCA Department

What is an Array?
We know very well that a variable is a container to store a value. Sometimes, developers are in a
position to hold more than one value in a single variable at a time. When a series of values is stored
in a single variable, then it is known as an array variable.

Array Declaration
Arrays are declared the same way a variable has been declared except that the declaration of an
array variable uses parenthesis. In the following example, the size of the array is mentioned in the
brackets.
'Method 1 : Using Dim Dim arr1() 'Without Size
'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5
'Method 3 : using 'Array' Parameter Dim arr3
arr3 = Array("apple","Orange","Grapes")
• Although, the Array size is indicated as 5, it can hold 6 values as array index starts from ZERO.
• Array Index Cannot be Negative.
• VBScript Arrays can store any type of variable in an array. Hence, an array can store an
integer, string or characters in a single array variable.

Assigning Values to an Array


The values are assigned to the array by specifying array index value against each one of the values
to be assigned. It can be a string.

Example – 75
<html> <body> <script language="vbscript">
<!-- Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Dim arr(5)
Value stored in Array index 2 : 100
arr(0) = "1" Value stored in Array index 3 : 2.45
arr(2) = 100 Value stored in Array index 4 : 7/10/2013

arr(3) = 2.45 Value stored in Array index 5 : 12:45:00 PM

arr(5) = #12.45 PM#


document.write("Value stored in Array index 0 : " & arr(0) & "<br />")
document.write("Value stored in Array index 1 : " & arr(1) & "<br />")
document.write("Value stored in Array index 2 : " & arr(2) & "<br />")
document.write("Value stored in Array index 3 : " & arr(3) & "<br />")
document.write("Value stored in Array index 4 : " & arr(4) & "<br />")
document.write("Value stored in Array index 5 : " & arr(5) & "<br />")
//--> </script> </body> </html>

VB Script
81
Nandha Arts and Science College PHP – I Unit BCA Department

Multi-Dimension Arrays
Arrays are not just limited to single dimension and can have a maximum of 60 dimensions. Two-
dimension arrays are the most commonly used ones.

Example – 76 In the following example, a multi-dimension array is declared with 3 rows and 4 columns.

<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim arr(2,3) ' Which has 3 rows and 4 columns
arr(0,0) = "Apple"
arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(0,3) = "pineapple"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
Value stored in Array index: 0, 1: Orange
arr(1,2) = "carrot"
Value stored in Array index: 2, 2: coffee
arr(1,3) = "tomato"
arr(2,0) = "potato"
arr(2,1) = "sandwitch"
arr(2,2) = "coffee"
arr(2,3) = "nuts"
document.write("Value in Array index 0,1 : " & arr(0,1) & "<br />")
document.write("Value in Array index 2,2 : " & arr(2,2) & "<br />")
//-->
</script>
</body> </html>

ReDim Statement
ReDim Statement is used to declare dynamic-array variables and allocate or reallocate storage space.
ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
• Preserve - An Optional parameter used to preserve the data in an existing array when you
change the size of the last dimension.
• varname - A Required parameter, which denotes Name of the variable, which should follow
the standard variable naming conventions.
• subscripts - A Required parameter, which indicates the size of the array.

VB Script
82
Nandha Arts and Science College PHP – I Unit BCA Department

Example – 77
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim a()
i=0
redim a(5) a(0)="XYZ" a(1)=41.25 a(2)=22
REDIM PRESERVE a(7) For i=3 to 7 XYZ
a(i)= i 41.25
22
Next 3
'to Fetch the output 4
5
For i=0 to ubound(a) Msgbox a(i) 6
Next 7
//-->
</script> </body> </html>

Error and Handling


There are three types of errors in programming:
(a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.

a) Syntax Errors
Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For example, the
following line causes a syntax error because it is missing a closing parenthesis:

Example – 78
<script type="text/vbscript">
<!--
dim x,y
x = "Vbtutorials" y = Ucase(x)
//-->
</script>

b) Runtime Errors
Runtime errors, also called exceptions, occur during execution, after interpretation.

Example – 79, the following line causes a runtime error because here syntax is correct but at
runtime it is trying to call fnmultiply, which is a non-existing function:

VB Script
83
Nandha Arts and Science College PHP – I Unit BCA Department

<script type="text/vbscript">
<!--
Dim x,y x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
Function fnadd(x,y)
fnadd = x+y
End Function
//-->
</script>

c) Logical errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result of
a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected. You cannot catch those errors, because it depends
on your business requirement what type of logic you want to put in your program. For example,
dividing a number by zero or a script that is written which enters into infinite loop.

Err Object
Assume if we have a runtime error, then the execution stops by displaying the error message. As a
developer, if we want to capture the error, then Error Object is used.

Example – 80 In the following example, Err.Number gives the error number and Err.Description
gives error description.
<script type="text/vbscript">
<!--
Err.Raise 6 ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear ' Clear the error.
//-->
</script> STATEMENT

-X-X-X-

VB Script
84
UNIT-II

Visual Basic Script


Input and Output
What is a Dialog Box?
VBScript allows the developers to interact with the user effectively. It can be a
message box to display a message to a user and an input box with which user
can enter the values.

VBScript MsgBox Function


The MsgBox function displays a message box and waits for the user to click a
button and then an action is performed based on the button clicked by the user.
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])

Parameter Description
Prompt - A Required Parameter. A String that is displayed as a message in the dialog box. The
maximum length of prompt is approximately 1024 characters. If the message extends to
more than a line, then we can separate the lines using a carriage return character.
Buttons - An Optional Parameter. A Numeric expression that specifies the type of buttons to display,
the icon style to use, the identity of the default button, and the modality of the message
box. If left blank, the default value for buttons is 0.
Title - An Optional Parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
Helpfile - An Optional Parameter. A String expression that identifies the Help file to use to provide
context-sensitive help for the dialog box.
Context - An Optional Parameter. A Numeric expression that identifies the Help context number
assigned by the Help author to the appropriate Help topic. If context is provided, help file
must also be provided.
Nandha Arts and Science College PHP – II Unit BCA Department

VBSCRIPT MSGBOX() FUNCTION BUTTONS


Constant Value Description
vb OK Only 0 Displays the OK button
vb OK Cancel 1 Displays the OK and Cancel buttons
vb Abort Retry Ignore 2 Displays the Abort, Retry, and Ignore buttons
vb Yes No Cancel 3 Displays the Yes, No, and Cancel buttons
vb Yes No 4 Displays the Yes and No buttons
vb Retry Cancel 5 Displays the Retry and Cancel buttons
vb Critical 16 Displays the Critical icon
vb Question 32 Displays the Question icon
vb Exclamation 48 Displays the Exclamation Mark icon
vb Information 64 Displays the Information icon

Example - 81
<html> <body>
<script language="vbscript" type="text/vbscript">
'Message Box with just prompt message
MsgBox("Welcome")
'Message Box with title, yes no and cancel Butttons
a = MsgBox("Do you like blue color?",3,"Choose options")
' Assume that you press No Button
document.write("The Value of a is " & a)
The Value of a is 7
</script></body></html>

VB Script 86
Nandha Arts and Science College PHP – II Unit BCA Department

VBScript InputBox Function


The Input Box function helps the user to get the values from
the user. After entering the values, if the user clicks the OK
button or presses ENTER on the keyboard, the Input Box
function will return the text in the text box. If the user clicks on the Cancel button, the function will
return an empty string (" ").

Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

Parameter Description
Prompt - A Required Parameter. A String that is displayed as a message in the dialog box. The
maximum length of prompt is approximately 1024 characters.
Title - An Optional Parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
Default - An Optional Parameter. A default text in the text box that the user would like to be displayed.
XPos - An Optional Parameter. The Position of X axis which represents the prompt distance from
left side of the screen horizontally. If left blank, the input box is horizontally centered.
YPos - An Optional Parameter. The Position of Y axis which represents the prompt distance from
left side of the screen vertically. If left blank, the input box is vertically centered.
Helpfile - An Optional Parameter. A String expression that identifies the Help file to use to provide
context-sensitive Help for the dialog box.
Context - An Optional Parameter. A Numeric expression that identifies the Help context number
assigned by the Help author to the appropriate Help topic. If context is provided, help file
must also be provided.

Example-82
<html>
<body>
<script language="vbscript" type="text/vbscript">
' Input Box with only Prompt
InputBox("Enter a number")
' Input Box with a Title
a=InputBox("Enter a Number","Enter Value")
msgbox a
' Input Box with a Prompt,Title and Default value
a=InputBox("Enter a Number","Enter Value",123)

VB Script 87
Nandha Arts and Science College PHP – II Unit BCA Department

msgbox a
' Input Box with a Prompt,Title,Default and XPos
a=InputBox("Enter your name","Enter Value",123,700)
msgbox a
‘ Input Box with a Prompt,Title and Default and YPos
a=InputBox("Enter your name","Enter Value",123,,500)
msgbox a
</script> </body> </html>

File Input/Output:
What are FSO Objects?
As the name suggests, FSO (File System Object) help the developers to work with drives, folders & files.
➢ An introduction to the Visual
Basic Scripting Edition (VB
Script) some basic coding,
starting with file input and
output (i.e. reading and
writing to / from files).

➢ VBScript is a language that joins (or glues) the different components of Microsoft's scripting
technologies together. These components are comprised of automation objects (COM objects
Component Object Model) that expose different parts of an application to the developer.
➢ Automation objects are what make it possible for you to programmatically access the file
system and Create, Modify, Delete, Open, and Close files for different purposes.

VB Script 88
Nandha Arts and Science College PHP – II Unit BCA Department

Objects and Collections


Object Type Description

Drive is an Object. Contains methods and properties that allow you to gather
Drive
information about a drive attached to the system

Drives is a Collection. It Provides a list of the drives attached to the system, either
Drives
physically or logically.

File is an Object. It Contains methods and properties that allow developers to


File
create, delete or move a file.

Files Files is a Collection. It Provides a list of all files contained within a folder.

Folder is an Object. It Provides methods and properties that allow developers to


Folder
create, delete or move folders.

Folders Folders is a Collection. It Provides a list of all the folders within a Folder.

TextStream TextStream is an Object. It enables developers to read and write text files.

Drive
Drive is an object, which provides access to the properties of a particular disk drive or network
share. The Following properties are supported by Drive object:
➢ AvailableSpace ➢ Path
➢ DriveLetter ➢ RootFolder
➢ DriveType ➢ SerialNumber
➢ FileSystem ➢ ShareName
➢ FreeSpace ➢ TotalSize
➢ IsReady ➢ VolumeName

Example-83 Drive - Win 8.1 Free Space:20,154,059 Kbytes


<html> <body>
<script language="vbscript" type="text/vbscript">
Dim oFS, drive, space
Set oFS = CreateObject("Scripting.FileSystemObject")
Set drive = oFS.GetDrive(oFS.GetDriveName("C:\"))
space = "Drive " &UCase(drvPath) & " - "
space = space &drive.VolumeName& " "
space = space & "Free Space: " &FormatNumber(drive.FreeSpace/1024, 0)
space = space & " Kbytes"
document.write space
</script>
</body> </html>

VB Script 89
Nandha Arts and Science College PHP – II Unit BCA Department

Drives
Drives is a collection, which provides details of all the drives attached to the system, either
physically or logically. It carries two properties: Count Property, Item Property.
Example - 84
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim oFS, d, dc, s, n
Set oFS = CreateObject("Scripting.FileSystemObject")
Set dc = oFS.Drives
C- Win 8.1::D-Personal ::
For Each d in dc
E-Common::F-Songs::5
n = ""
s = s & d.DriveLetter& " - "
If d.DriveType = 3 Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
Else
n = "Drive not available"
End If
s = s & n & "::"
Next
document.write s
document.write dc.count
</script> </body> </html>

File
File is an Object, which contains both properties and methods that allow the developers to
create, delete or move a file.
Methods
• Open as Text Stream • Copy • Delete • Move
Properties
• Attributes • Drive • Name • Path
• Date Created • Parent Folder • Short Name • Short Path
• Date Last Accessed • Date Last Modified • Size • Type

VB Script 90
Nandha Arts and Science College PHP – II Unit BCA Department

Example – 85
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("C:\user.vbs")
document.write "Line 1: "&f.DateCreated& "<br />"
document.write "Line 2: "&f.Attributes& "<br />"
document.write "Line 3: "&f.DateLastAccessed& "<br />"
document.write "Line 4: "&f.DateLastModified& "<br />"
document.write "Line 5: "&f.Drive& "<br />"
document.write "Line 6: "&f.Name& "<br />"
document.write "Line 7: "&f.ParentFolder& "<br />"
document.write "Line 8: "&f.Path& "<br />"
document.write "Line 9: "&f.ShortName& "<br />"
document.write "Line 10: "&f.ShortPath& "<br />"
document.write "Line 11: "&f.Size& "<br />"
document.write "Line 12: "&f.Type& "<br />"
f.copy ("D:\") & "<br />" 'copying to file to another location'
f.Move ("E:\") & "<br />" 'Move the file to another location'
f.Delete ("D:\") & "<br />" 'Delete to file from one location'
</script> </body> </html>

Line 1: 08/02/17 04:54:44 Line 7: C:\


Line 2: 32 Line 8: C:\user.vbs
Line 3: 08/02/17 04:54:44 Line 9: user.vbs
Line 4: 04/18/16 12:13:47 Line 10: C:\user.vbs
Line 5: C: Line 11: 587
Line 6: user.vbs Line 12: VBScript Script File

Files
Files is a collection, which provides a list of all files contained within a folder.
Properties • Count • Item

VB Script 91
Nandha Arts and Science College PHP – II Unit BCA Department

Example – 86
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim fso, f, f1, fc, s
Set oFS = CreateObject("Scripting.FileSystemObject")
'get the folder by giving its path
Set f = oFS.GetFolder("D:\PROJECT\")
Set fc = f.Files
'Get Item
Set s = fc.Item("sendmail.vbs")
'Get Count
x = fc.Count D:\PROJECT\sendmail.vbs
document.write s 6
document.write x
</script> </body>
</html>

Folder
Folder is an Object, which contains both properties and methods that allow the developers to
create, delete or move a folder.

Methods
• Copy • Delete • Move • Create Text

File Properties
➢ Attributes ➢ Drive ➢ Parent Folder ➢ Size
➢ Date Created ➢ Files ➢ Path ➢ Sub Folders
➢ Date Last Accessed ➢ Is Root Folder ➢ Short Name ➢ Type
➢ Date Last Modified ➢ Name ➢ Short Path

Folders : Folders is a collection of all Folder Objects within a Folder object.


Methods Add
Properties -> Count -> Item

VB Script 92
Nandha Arts and Science College PHP – II Unit BCA Department

Example – 87
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim fso, f, fc, nf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("D:\PROJECT")
Set fc = f.SubFolders
folderName = "Test_Folder"
If folderName <> "" Then
Set nf = fc.Add(folderName)
Else
Set nf = fc.Add("New Folder")
End If
</script> </body> </html>

TextStream
TextStream object helps the developers to work with text files seamlessly. Developers can read, write
or append the contents to the text file using the text stream object.

Syntax
TextStream.{property | method( )}

Example – 88
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTextFile
Set objTextFile = objFSO.CreateTextFile("D:\Testfile.txt")
objTextFile.Close
ConstForAppending = 8
Set objTextFile=objFSO.OpenTextFile("D:\Testfile.txt",ForAppending,True)
objTextFile.WriteLine "Welcome to VBScript Programming"
objTextFile.Close
Welcome to VBScript Programming
Set objTextFile = Nothing
Set objFSO = Nothing
</script> </body> </html>

VB Script 93
Nandha Arts and Science College PHP – II Unit BCA Department

Data Validation
➢ Data validation is the process of ensuring that a program
operates on Clean, Correct and Useful data. It use
routines often called “Validation rules” or “Check
routines”, that check for correctness, meaningfulness,
are security of data that are input to the system. The rules
may be implemented through the automated facilities of
a data dictionary, or by the inclusion of explicit application
program validation logic.
➢ Data validation is intended to provide certain well-
defined guarantees for fitness, accuracy, and consistency for any of various kinds of user input
into an applications or automated system.
➢ Data validation rules can be defined and designed using any of various methodologies, and be
deployed in any of various contexts. Set Datavalidation
➢ For business applications, data validation
can be defined through declarative data
integrity rules, or procedure-based
business rules. Data that does not conform
to these rules will negatively affect
business process execution. Therefore,
data validation should start with business
process definition and set of business rules
within this process. Rules can be collected through the requirements capture exercise.
➢ Data validation rules may be defined, designed and deployed.
Definition and design contexts:
✓ as a part of requirements-gathering phase in a software
engineering or designing a software specification
✓ as part of an operations modeling phase in business
process modeling
Deployment contexts:
✓ as part of a user-interface
✓ as a set of programs or business-logic routines in a programming language
✓ as a set of stored-procedures in a database management system

VB Script 94
Nandha Arts and Science College PHP – II Unit BCA Department

Different kinds of validation


In evaluating the basics of data validation, generalizations can be made regarding the different
types of validation, according to the scope, complexity, and purpose of the various validation
operations to be carried out.
For example:
1. Data type validation; 2. Range and constraint validation;
3. Code and Cross-reference validation, 4. Structured validation

Validation methods
Allowed character checks: Checks that ascertain that only expected characters are present in a
field. For example a numeric field may only allow the digits 0-9, the
decimal point and perhaps a minus sign or commas. A text field such
as a < and >, an e-mail address might require at least one @ sign and
various other structural details.
Batch totals: Checks for missing records. Numerical fields may be added together
for all records in a batch. The batch total is entered and the computer
checks that the total is correct, e.g., add the 'Total Cost' field of a
number of transactions together.
Cardinality check: Checks that record has a valid number of related records. For
example if contact record in Payroll database is marked as "former
employee", then this record must not have any associated salary
payments after the date on which employee left organization.
Check digits: Used for numerical data. An extra digit is added to a number which is
calculated from the digits. The computer checks this calculation when
data are entered. For example the last digit of an ISBN for a book is a
check digit calculated modulus 10.
Consistency checks: Checks fields to ensure data in these fields corresponds, e.g., If Title
= "Mr.", then Gender = "M".
Control totals: This is a total done on one or more numeric fields which appears in
every record. This is a meaningful total, e.g., add the total payment
for a number of Customers.
Cross-system consistency checks: Compares data in different systems to ensure it is consistent, e.g.,the
address for the customer with the same id is the same in both
systems.
Data type checks: Checks the data type of the input and give an error message if the
input data does not match with the chosen data type, e.g., In an input

VB Script 95
Nandha Arts and Science College PHP – II Unit BCA Department

box accepting numeric data, if the letter 'O' was typed instead of the
number zero, an error message would appear.
File existence check: Checks that a file with a specified name exists. This check is essential
for programs that use file handling.
Format or picture check: Checks that the data is in a specified format (template), e.g., dates
have to be in the format DD/MM/YYYY. Regular expressions should
be considered for this type of validation.
Hash totals: This is just a batch total done on one or more numeric fields which
appears in every record. This is a meaningless total, e.g., add the
Telephone Numbers together for a number of Customers.
Limit check: Unlike range checks, data are checked for one limit only, upper OR
lower, e.g., data should not be greater than 2 (<=2).
Logic check: Checks that an input does not yield a logical error, e.g., an input value
should not be 0 when it will divide some other number somewhere in
a program.
Presence check: Checks that important data is actually present and have not been
missed out, e.g., customers may be required to have their telephone
numbers listed.
Range check: Checks that the data is within a specified range of values, e.g., the
month of a person's date of birth should lie between 1 and 12.
Referential integrity: In modern Relational database values in two tables can be linked
through foreign key and primary key.
Spelling and grammar check: Looks for spelling and grammatical errors.
Uniqueness check: Checks that each value is unique. This can be applied to several fields
(i.e. Address, First Name, and Last Name).
Table look up check: A table look up check takes the entered data item and compares it to
a valid list of entries that are stored in a database table.

Integration with Forms


Simple Validation:
You can use visual basic scripting edition to do much of the form processing that you’d usually have
to do on a server. You can also do things that just can’t be done on the server.
The HTML code is for a text box and a button. If you use Microsoft internet explorer to view the page,
you will see a small text box with a button next to it.

VB Script 96
Nandha Arts and Science College PHP – II Unit BCA Department

Example – 89
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Validate
Dim TheForm
Set TheForm = Document.forms("ValidForm")
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.
Text1.Value > 10 Then
MsgBox "Please enter a number between 1& 10."
Else
MsgBox "Thank you."
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
//-->
</SCRIPT> </HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<form id="ValidForm" action="nothing.asp" onsubmit="Validate();
return false;" language="jscript">
Enter a value between 1 and 10:
<input name="Text1" TYPE="TEXT" SIZE="2">
<input name="Submit" TYPE="Submit" VALUE="Submit">
</form> </BODY> </HTML>

How to validate your Forms:


The processes to validate the forms are as under. The two things should be checked.
1. All of the required data is entered. 2. The data entered is valid or not

Example – 90
<html> <head>
<title>VB Script Example</title>
<script language="”VBScript”">
Sub cmdSubmit_onClick
‘Check whether user has entered the required text or not.

VB Script 97
Nandha Arts and Science College PHP – II Unit BCA Department

If (Len(document.myform.txtage.value))) then
MsgBox “Please enter your age before submitting”
Exit Sub
End If
‘Check the data entered is numeric or not.
If (Not(IsNumeric(document.myform.txtage.value))) then
MsgBox “Please enter numeric data”
Exit Sub
End If
‘Check the range of the age
If (document.myform.txtage.value< 0) or (document.myform.txtage.value> 100) then
MsgBox “Age entered is Invalid”
Exit Sub
End If Please enter
‘If all is fine submit the data your age before
submitting
MsgBox “Thanks for providing your age”
document.myform.submit
End sub
</script> </head>
<body>
Please enter Age entered is
<form name="“myform”" id="“myform”"> numeric data Invalid
<table>
<tr>
<td>please enter your age:</td>
<td><input type="“text”" name="“txtage”" size="”2”"></td>
</tr>
<tr>
<td></td>
<td><input name="Submit" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

VB Script 98
Nandha Arts and Science College PHP – II Unit BCA Department

• In the above example first we are checking whether the user has entered any value or not. If
he has not entered any value we will prompt to enter any value.
• Second validation is that if he has entered any value, just check whether the data entered is
numeric or not.
• If the next step we are validating that the age value is entered as per the prescribed range or
not. At last if all the validations are met by the user, he will be shown a message that “Thanks
for providing your age” and this data will be submitted to the web server.

ActiveX Control & Scripting:


ActiveX is a software framework created by Microsoft that adapts its earlier Component Object Model
(COM) and Object Linking and Embedding (OLE) technologies for content downloaded from a
network, particularly from the World Wide Web. Microsoft introduced ActiveX in 1996. In principle,
ActiveX is not dependent on Microsoft Windows operating systems, but in practice most ActiveX
controls only run on Windows. Most also require the client to be running on an x86-based computers
because ActiveX controls contain compiled code.
A create applications without a development language, such as C++ or Visual Basic, and controls, like
menus, buttons, and toolbars, you can't create fully interactive Web pages without a scripting
language and controls, which is where ActiveX and VBScript enter the picture. ActiveX and VBScript
are the perfect partners.
ActiveX supplies the foreground functions, like the menus, buttons, and other controls users see,
hear, and experience; VBScript provides the background functions, gluing the controls together and
allowing them to call script methods and respond to events.

Example – 91
<html> <head> <script language="VBScript">
<!-- Public Sub buttonHandler()
dim myVar
myVar = " ActiveX Control"

MsgBox myVar
End Sub ActiveX Control

//--> </script> </head>


<body>
<form name="Crap">
<input type=button name="button1"
onClick="buttonHandler" value="Hello World" />
</form> </body> </html>

VB Script 99
Nandha Arts and Science College PHP – II Unit BCA Department

What is an ActiveX control?


ActiveX is a software component of Microsoft Windows. If you have Internet Explorer, then ActiveX is
already installed on your computer. ActiveX controls are small programs, sometimes called add-ons
that are used on the Internet. They can enhance your browsing experience by allowing animation or
they can help with tasks such as installing security updates at Microsoft Update.
You can decide whether or not you want to download ActiveX controls on a case by case basis. Some
websites require you to install ActiveX controls to view or perform certain tasks on them, but there
can be potential risks. Cybercriminals may develop their own ActiveX controls and can damage
computers if users visit web pages that contain malicious ActiveX software.
When you visit a site that uses an ActiveX control, Internet Explorer asks if you want to install the
ActiveX control. You can then choose to install the ActiveX control or learn about the risks.

ActiveX Scripting
You have already seen that web
browsers support a plain text syntax,
known as HTML, for displaying
information. HTML is a simple
language and, as such, provides few
mechanisms for extended interaction.
Some controls, such as buttons, are
supported basically; however, more
advanced user interface controls,
such as spinners, calendars, and grids, are not implemented.
In an effort to provide a completely interactive environment, Microsoft has introduced a standard for
including any scripting language within an HTML page. This standard is called ActiveX Scripting. ActiveX
Scripting is a language-independent standard that defines the relationship between a scripting host
and a scripting engine. A scripting engine is nothing more than an in-process ActiveX component,
formerly called an OLE server that conforms to the ActiveX Scripting specification. A scripting host is
an application that uses the scripting
engine. An example of a scripting host
is the Microsoft Internet Explorer 3.0.
ActiveX Scripting begins when an in-
process ActiveX component
representing the scripting engine is
instantiated inside the process space

VB Script 100
Nandha Arts and Science College PHP – II Unit BCA Department

of the Internet Explorer. After the scripting engine has been built by the Internet Explorer, it is loaded
with commands for execution. The commands themselves, called the script, live inside the actual
HTML page between the two tags <SCRIPT>and </SCRIPT>. After the script has been loaded into the
engine, the Internet Explorer runs the script through the engine. This action results in the functionality
defined by the commands in the code.

Scripting host Scripting engine


(Internet Explorer 3.0) (vbscript.dll)
ActiveX Scripting

ActiveX Scripting.
Microsoft Visual Basic, Scripting Edition, is implemented with the scripting engine named vbscript.dll.
The VBScript engine and the Internet Explorer are not fundamentally joined therefore, vbscript.dll can
be used in any application that is an ActiveX scripting host. The VBScript engine understands the
VBScript language, which is nothing more than a subset of the existing Visual Basic for Applications
language. With the support of the Internet Explorer, VBScript can read and modify HTML form
elements, perform event handling, interact with the browser, and automate any ActiveX component.

Using ActiveX Controls in VBScript


The ActiveX controls, which are essentially limited OCX controls that Microsoft has developed or
distributes for use with VBScript. The ability to use embedded ActiveX controls is one of the most
powerful VBScript techniques. In fact, some people consider VBScript simply a means of making
ActiveX controls work in Web pages. We will look at some of the most popular ActiveX controls and
then go into more depth on three of them: grid controls, graph controls, and multimedia controls.
Examples 3-D buttons, 3-D frames and panels, Grid controls, Graph controls, 3-D checkboxes, AVI file
controls, Multimedia controls, Spin buttons, 3-D option buttons, Sliders, Key state controls, Rich text
controls, Progress bars.

---x---x---x---

VB Script 101
UNIT-III

JAVA SCRIPT
Form
HTML pages may include forms, which allow the user to fill out information and send it to the server.
A moderately complicated website can easily include anywhere from 10 to 200 resources. To be able
to fetch those quickly, browsers will make several requests simultaneously, rather than waiting for the
responses one at a time. Such documents are always fetched using GET requests.

Example – 92
<html>
<body>
<form method ="GET" action =" example/message.html">
<p>Name: <input type="text" name="name"></p>
<p>Message:<br><textarea name=" message"></textarea ></p>
<p><button type=" submit">Send </button ></p>
</form> </body> </html>
This code describes a form with two fields: a small one asking for a name and a larger one to write a
message in. When you click the Send button, the information in those fields will be encoded into a
query string

Fields
A web form consists of any number of input fields grouped in a <form> tag. HTML allows a number
of different styles of fields, ranging from simple on/off checkboxes to drop-down menus and fields
for text input. A lot of field types use the <input> tag. This tag’s type attribute is used to select the
field’s style. These are some commonly used <input> types:
text A single-line text field
password Same as text but hides the text that is typed
checkbox (Part of) a multiple-choice field
radio An on/off switch
file Allows the user to choose a file from their computer
Form fields do not necessarily have to appear in a <form> tag.
Nandha Arts and Science College PHP –III Unit BCA Department

Form Validation
What is Validation?
Validation means check the input submitted by the user. There are two types of validation are
available in PHP. They are as follows −
Client-Side Validation − Validation is performed on
the client machine web browsers.
Server Side Validation − After submitted by data, The
data has sent to a server and perform validation
checks in server machine.
JavaScript can be used to validate data in HTML forms
before sending off the content to a server.
Form data that typically are checked by a JavaScript
could be:
• Has the user left required fields empty?
• Has the user entered a valid e-mail address?
• Has the user entered a valid date?
• Has the user entered text in a numeric field?
Form validation normally used to occur at the
server, after the client had entered all the necessary data and then pressed the Submit button. If
the data entered by a client was incorrect or was simply missing, the server would have to send all
the data back to the client and request that the form be resubmitted with correct information. This
was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web
server. Form validation generally performs two functions.
Basic Validation -
First of all, the form must be checked to make sure all the mandatory fields are filled in. It
would require just a loop through each field in the form and check for data.
Data Format Validation -
Secondly, the data that is entered must be checked for correct form and value. Your code must
include appropriate logic to test correctness of data.
Example - 93
We will take an example to understand the process of
validation. Here is a simple form in html format.
<html>
<head>
<title> Form Validation</title>
<script language = “Javascript” type="text/javascript">
<!--
// Form validation code will come here.

Java Script 103


Nandha Arts and Science College PHP –III Unit BCA Department

//-->
</script> </head>
<body>
<form action="contact.html" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr> <td align="right">Name</td>
<td> <input type="text" name="Name" /></td> </tr>
<tr> <td align="right"> EMail</td>
<td> <input type="text" name="EMail" /></td> </tr>
<tr> <td align="right">Zip Code</td>
<td> <input type="text" name="Zip" /></td> </tr>
<tr> <td align="right">Country</td>
<td> <select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option> </select> </td> </tr>
<tr> <td align="right"></td>
<td> <input type="submit" value="Submit" /></td> </tr>
</table> </form> </body> </html>
Basic Form Validation
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate
data when on_Submit() event is occurring. The following code shows the implementation of this
validate() function.
Example - 94
<html> <head> <script>
function validateForm()
{
var x = document.forms["myForm"]["fname"].value;
if (x == "")
{
alert("Name must be filled out");
return false;
}
}
</script> </head> <body>
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form> </body> </html>

Java Script 104


Nandha Arts and Science College PHP –III Unit BCA Department

(OR)
Example - 94
<script language = “Javascript” type="text/javascript">
<!—
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Required Fields:
The function below checks if the field has been left empty. If the field is blank, an alert box
alerts a message, the function returns false, and the form will not be submitted.

Java Script 105


Nandha Arts and Science College PHP –III Unit BCA Department

E-mail Validation:
The function below checks if the content has the general syntax of Valid

an email. This means that the input data


must contain @ sign and at least one
dot (.).
Also, @ must not be the first character
of the email address, and the last dot
must be present after @ sign, and
minimum 2 characters before the end.
Invalid invalid email id

Example - 95
function validateForm()
{
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1|| dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
JavaScript SSI and Cookies:
What is a Cookie?
A cookie is an amount of information that persists between a server-side and a client-side. A web
browser stores this information at the time of browsing. A cookie contains the information as a string
generally in the form of a name-value pair separated by semi-colons. It maintains the state of a user
and remembers the user's information among all the web pages.
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's
computer. They are typically used to keeping track of information such as username that the site can
retrieve to personalize the page when user visit the website next time.

Java Script 106


Nandha Arts and Science College PHP –III Unit BCA Department

Web Browsers and Servers use


HTTP protocol to communicate and
HTTP is a stateless protocol. But for a
commercial website, it is required to
maintain session information among
different pages. For example, one user
registration ends after completing many
pages. But how to maintain users' session information across all the web pages. In many situations,
using cookies is the most efficient method of remembering and tracking preferences, purchases,
commissions, and other information required for better visitor experience or site statistics.
• A cookie is a variable that is stored on the visitor's computer. Each time the same computer
requests a page with a browser, it will send the cookie too.
• With JavaScript, you can both create and retrieve cookie values.

How Cookies Works?


o When a user sends a request to the server, then each of that request is treated as a new
request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that request
automatically. Due to the cookie, the server recognizes the users.
o Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive.
Now, when the visitor arrives at another page on your site, the browser sends the same cookie
to the server for retrieval. Once retrieved, your server knows/remembers what was stored
earlier.

Java Script 107


Nandha Arts and Science College PHP –III Unit BCA Department

Cookies are a plain text data record of 5 variable-length fields:


• Expires: The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
• Domain: The domain name of your site.
• Path: The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
• Secure: If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
• Name=Value: Cookies are set and retrieved in the form of key-value pairs.
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript
can read, create, modify, and delete the cookies that apply to the current web page.

Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object, which
looks like this.
document.cookie = "key1=value1; key2=value2; expires=date";

Here the expires attribute is optional. If you provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.

Example – 96
<html> <head> <script language = “Javascript” type="text/javascript">
<!--
function WriteCookie()
{
if ( document.myform.customer.value == "" ) {
alert ("Enter some value!");
return;
}

Java Script 108


Nandha Arts and Science College PHP –III Unit BCA Department

cookievalue= escape(document.myform.customer.value) + ";";


document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
} //--> </script> </head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onClick="WriteCookie();"/>
</form> </body></html>

Setting Cookies : name=karthi;

Now your machine has a cookie called name. You can set multiple cookies using multiple key=value
pairs separated by comma.

Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is
the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows:

Example - 97
<html>
<head>
<script language = “Javascript” type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++)
Java Script 109
Nandha Arts and Science College PHP –III Unit BCA Department

{
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script> </head> <body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form> </body>
</html>
Note: Here length is a method of Array class
which returns the length of an array.

All Cookies : name=Raja; expires=Sun, 18 Aug 2019 15:27:16 GMT;


__utma=55973678.1445616820.1563463252.1563463252.1563463252.1; __utmb=55973678; __utmc=55973678;
__utmz=55973678.1563463252.1.1.utmccn=(referral)|utmcsr=google.co.in|utmcct=/|utmcmd=referral;
PHPSESSID=ing822qg9keeqd665j811tgc01; _ga=GA1.2.1445616820.1563463252; _gid=GA1.2.185904291.1563463451;
_gat_gtag_UA_232293_6=1Key is : name and Value is : RajaKey is : expires and Value is : Sun, 18 Aug 2019 15:27:16
GMTKey is : __utma and Value is : 55973678.1445616820.1563463252.1563463252.1563463252.1Key is : __utmb and
Value is : 55973678Key is : __utmc and Value is : 55973678Key is : __utmz and Value is :
55973678.1563463252.1.1.utmccnKey is : PHPSESSID and Value is : ing822qg9keeqd665j811tgc01Key is : _ga and Value is :
GA1.2.1445616820.1563463252Key is : _gid and Value is : GA1.2.185904291.1563463451Key is : _gat_gtag_UA_232293_6
and Value is : 1

Note: The above code will display all the cookies set on your machine.

Setting Cookies Expiry Date


You can extend the life of a cookie beyond the current browser session by setting an
expiration date and saving the expiry date within the cookie. This can be done by setting the
‘expires’ attribute to a date and time.

Example – 98 It illustrates how to extend the expiry date of a cookie by 1 Month.


<html> <head>
<script language = “Javascript” type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
Java Script 110
Nandha Arts and Science College PHP –III Unit BCA Department

cookievalue = escape(document.myform.customer.value) + ";"


document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.

Example – 99 it illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

<html> <head> <script language = “Javascript” type="text/javascript">


<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//--> </script> </head>
<body>

Java Script 111


Nandha Arts and Science College PHP –III Unit BCA Department

<form name="formname" action="">


Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onClick="WriteCookie()"/>
</form> </body> </html>

Setting Cookies : name=;

Java Script: Server side Includes (SSI):


 A Server Side Include (SSI) allows you to write some commonly used code once and have the
server insert it into the pages for you. Many Web sites use these SSIs to provide common
components such as a header, footer, navigation bar, or search bar. The main advantage of
them is that they provide a single point of change, no risk of missing an occurrence in the
site—similar to the benefits of using CSS or JavaScript files.
 SSI files themselves can have
any extension, but by default
a page that uses one or more
of them has the extension
.SHTML to signify to the Web
server that this page needs
to be handled differently to a
standard HTML file.
 Server Side Includes, are a way to tell the server to insert something into a web page before
it is sent to the viewer. What is inserted may be the content of a plain text file or it may be
the output generated by
another program running on
the server such as the
processing of a form return
using a JavaScript & PERL
script.
 SSIs do not work with all
servers, and even if the
server is SSI-capable, it must

Java Script 112


Nandha Arts and Science College PHP –III Unit BCA Department

be configured to allow SSIs to run. The most popular web server is currently Apache which, as
a development of the WWW server, can be seen as the server for which SSIs were created.
 If your server is already configured for them, SSIs are incredibly(very) simple to use. For
example, to include the same code for a navigation bar on every page in your site, save the
required code in a plain text file - just the code, no <html>, <head> or <body>
tags (unless they are part of the code to be included) - and call it anything.
 SSI-enabled servers recognize which pages which require parsing by their filename extension.
 SSIs can be a powerful tool for site management and are especially useful for the maintenance
of sites which require frequent changes. They are also particularly valuable when you are
weaning yourself off using frames.
 SSI includes, there are six built-in objects. They are,
1. Server object. 2. Project object. 3. Client object.
4. Request object. 5. File object. 6. Database object.

Frames and Windows Elements


 HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document. A collection of frames in the browser
window is known as a frameset. The window is divided into frames in a similar way the
tables are organized: into rows and columns.
 The small collection of HTML elements that deal with windows or, more specifically, frames
that allow multi-windowed layouts (using the frameset) or floating window effects.
 While the elements contained in this section are used less and less in modern-day web design,
they’re still valid, and there are still many web sites that use these elements today as they
have for years.
 The frame element defines one particular window within a frameset collection. In a typical
frameset construction, one frame might be used for the purposes of navigation, with another
frame used for presenting content.
 Each individual frame in a frameset can have different behaviors/appearance, such as
scrolling, the ability to resize the frame boundaries and border style.
Note that the above example shows the XHTML syntax, which requires a trailing forward
slash ("/") character to pass as valid XHTML.
<frameset rows="100,*" >
<frame src="header.html">
<frame src="home.html">
</frameset>
Java Script 113
Nandha Arts and Science College PHP –III Unit BCA Department

Disadvantages of Frames
There are few drawbacks with using frames, so it's never recommended to use frames in your webpages:
▪ Some smaller devices cannot cope with frames often because their screen is not big enough
to be divided up.
▪ Sometimes your page will be displayed differently on different computers due to different
screen resolution.
▪ The browser's back button might not work as the user hopes.
▪ There are still few browsers that do not support frame technology.

Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag. The <frameset> tag defines,
how to divide the window into frames. The rows attribute of <frameset> tag defines horizontal frames
and cols attribute defines vertical frames. Each frame is indicated by <frame> tag and it defines which
HTML document shall open into the frame.

Example 100 :- To create three horizontal frames:


<html>
<head>
<title> HTML Frames</title>
</head>
<frameset rows="10%,80%,10%">
<frame name="top"
src="/html/top_frame.htm" />
<frame name="main" src="/html/main_frame.htm" />
<frame name="bottom" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body> </noframes> </frameset> </html>

Example 101 :- Let's put the above example as follows, here we replaced rows attribute by
cols and changed their width. This will create all the three frames vertically:
<html>
<head> <title>HTML Frames</title> </head>
<frameset cols="25%,50%,25%">
<frame name="left" src="/html/top_frame.htm" />
<frame name="center" src="/html/main_frame.htm" />
<frame name="right" src="/html/bottom_frame.htm" />

Java Script 114


Nandha Arts and Science College PHP –III Unit BCA Department

<noframes>
<body> Your browser does not support frames.
</body> </noframes> </frameset> </html>

<Frameset> Tag Attributes


Attribu Description
te Specifies how many columns are contained in the frameset and the size of each column. You can specify
the width of each column in one of the four ways: A percentage of the browser window. For example,
cols to create three vertical frames, use cols="10%, 80%,10%".
Using a wildcard symbol. For example, to create three vertical frames, use cols="10%, *,10%". In this
case wildcard takes remainder of the window. As relative widths of the browser window. For
example, to create three vertical frames, use cols="3*,2*,1*".

rows This attribute works just like the cols attribute and takes the same values, but it is used to specify the
rows in the frameset. For example, to create two horizontal frames, use rows="10%, 90%". You can
specify the height of each row in the same way as explained above for columns.
border This attribute specifies the width of the border of each frame in pixels. For example, border="5". A
value of zero means no border.
Frame This attribute specifies whether a three-dimensional border should be displayed between frames.
border This attribute takes value either 1 (yes) or 0 (no). For example frameborder="0" specifies no border.

Frame This attribute specifies the amount of space between frames in a frameset. This can take any integer
spacing value. For example framespacing="10" means there should be 10 pixels spacing between each frames.
The <frame> Tag Attributes Following are the important attributes of <frame> tag:
Attribute Description

src This attribute is used to give the file name that should be loaded in the frame. Its value can be any
URL. For example, src="/html/top_frame.htm" will load an HTML file available in html directory.
This attribute allows you to give a name to a frame. It is used to indicate which frame a document
name should be loaded into. This is especially important when you want to create links in one frame that
load pages into an another frame, in which case the second frame needs a name to identify itself as
the target of the link.
This attribute specifies whether or not the borders of that frame are shown; it overrides the value
Frame
given in the frameborder attribute on the <frameset> tag if one is given, and this can take values
border either 1 (yes) or 0 (no).
Margin This attribute allows you to specify the width of the space between the left and right of the frame's
width borders and the frame's content. The value is given in pixels. For example marginwidth="10".
Margin This attribute allows you to specify the height of the space between the top and bottom of the frame's
height borders and its contents. The value is given in pixels. For example marginheight="10".
noresize By default, you can resize any frame by clicking and dragging on the borders of a frame. The noresize
attribute prevents a user from being able to resize the frame. For example noresize="noresize".
scrolling This attribute controls the appearance of the scrollbars that appear on the frame. This takes values
either "yes", "no" or "auto". For example scrolling="no" means it should not have scroll bars.

longdesc This attribute allows you to provide a link to another page containing a long description of the
contents of the frame. For example longdesc= "framedescription.htm"

Java Script 115


Nandha Arts and Science College PHP –III Unit BCA Department

Browser Support for Frames


If a user is using any old browser or any browser, which does not support frames then <noframes>
element should be displayed to the user.
So you must place a <body> element inside the <noframes> element because the <frameset> element
is supposed to replace the <body> element, but if a browser does not understand <frameset> element
then it should understand what is inside the <body> element which is contained in a <noframes>
element.
Frame's name and target attributes
One of the most popular uses of frames is to place navigation bars in one frame and then load main
pages into a separate frame.

Example – 102 Let's see following example where a test.htm file has following code:
<html>
<head>
<title>HTML Target Frames</title>
</head>
<frameset cols="200, *">
<frame src="/html/menu.htm" name="menu_page" />
<frame src="/html/main.htm" name="main_page" />
<noframes>
<body>
Your browser does not support frames.
</body> </noframes>
</frameset> </html>
Here, we have created two columns to fill with two frames. The first frame is 200 pixels wide and will
contain the navigation menu bar implemented by menu.htm file. The second column fills in
remaining space and will contain the main part of the page and it is implemented by main.htm file.
For all the three links available in menu bar, we have mentioned target frame as main_page, so
whenever you click any of the links in menu bar, available link will open in main page.

Example – 103 Following is the content of menu.htm file


<html>
<body bgcolor="#4a7d49">
<a href="http://www.google.com" target="main_page">Google</a>
<br /><br />
<a href="http://www.microsoft.com" target="main_page">Microsoft</a>
<br /><br />

Java Script 116


Nandha Arts and Science College PHP –III Unit BCA Department

<a href="http://news.bbc.co.uk" target="main_page">BBC News</a>


</body> </html>

Example – 104 Following is the content of main.htm file:


<html>
<body bgcolor="#b5dcb3">
<h3>This is main page and content from any link will be displayed
here.</h3>
<p>So now click any link and see the result.</p>
</body> </html>

Now you can try to click links available in the left panel and see the result. The target
attribute can also take one of the following values:
Option Description
_self Loads the page into the current frame.

_blank Loads a page into a new browser window.opening a new window.

Loads the page into the parent window, which in the case of a single frameset
_parent
is the main browser window.
_top Loads the page into the browser window, replacing any current frames.
targetframe Loads the page into a named targetframe.

MIME Types:
 Multipurpose Internet Mail Extensions, a specification for formatting non-ASCII messages so
that they can be sent over the Internet. Many e-mail clients now support MIME, which enables
them to send and receive graphics, audio, and video files via the Internet mail system. In
addition, MIME supports messages in character sets other than ASCII.
 There are many predefined MIME types, such as GIF graphics files and PostScript files.
It is also possible to define your own MIME types.
 In addition to e-mail applications, Web browsers also support various MIME types.
This enables the browser to display or output files that are not in HTML format.
 MIME was defined in 1992 by the Internet Engineering Task Force (IETF). A new
version, called S/MIME, supports encrypted messages.

Java Script 117


Nandha Arts and Science College PHP –III Unit BCA Department

A Simple Explanation of MIME Types


A MIME type consists of two parts.
▪ The first part defines what web content is at a high level (image, video, application, etc.);
▪ The second part defines what web content is at a more detailed level (png, avi, javascript, etc.).
This two-part definition is needed so clients like
web browsers can translate content that servers
give them into terms users like us can experience.
Here are some basic examples of how MIME
types are displayed:
▪ image/png
▪ video/avi
▪ application/javascript

What is a MIME type?


MIME stands for "Multipurpose Internet Mail Extensions”. It's a way of identifying files on the Internet according
to their nature and format. For example, using the "Content-type" header value defined in a HTTP response, the
browser can open the file with the proper extension/plugin.

What is a Content-Type?
A "Content-type" is simply a header defined in
many protocols, such as HTTP, that makes use of
MIME types to specify the nature of the file
currently being handled.
Through the use of the multipart type, MIME
allows mail messages to have parts arranged in a
tree structure where the leaf nodes are any non-
multipart content type and the non-leaf nodes
are any of a variety of multipart types. This
mechanism supports:
 Simple text messages using text/plain (the default value for "Content-Type: ")
 Text plus attachments (multipart/mixed with a text/plain part and other non-text parts). A MIME
message including an attached file generally indicates the file's original name with the "Content-
disposition:" header, so the type of file is indicated both by the MIME content-type and the (usually OS-
specific) filename extension
 Reply with original attached (multipart/mixed with a text/plain part and the original message).

Java Script 118


Nandha Arts and Science College PHP –III Unit BCA Department

 Alternative content, such as a message sent in both plain text and another format such as
HTML (multipart/alternative with the same content in text/plain and text/html forms)
 Image, audio, video and application (for example, image/jpeg, audio/mp3, video/mp4, and
application/MS Word and so on)

 Many other message constructs.

Extension Kind of document MIME Type

.aac AAC audio file audio/aac

.avi AVI: Audio Video Interleave video/x-msvideo

.azw Amazon Kindle eBook format application/vnd.amazon.ebook

.bin Any kind of binary data application/octet-stream

.bz BZip archive application/x-bzip

.css Cascading Style Sheets (CSS) text/css

.csv Comma-separated values (CSV) text/csv

.doc Microsoft Word application/msword

.eot MS Embedded OpenType fonts application/vnd.ms-fontobject

.epub Electronic publication (EPUB) application/epub+zip

.gif Graphics Interchange Format (GIF) image/gif

.htm, .html HyperText Markup Language (HTML) text/html

.ico Icon format image/x-icon

.ics iCalendar format text/calendar

.jar Java Archive (JAR) application/java-archive

.jpeg, .jpg JPEG images image/jpeg

.js JavaScript (ECMAScript) application/javascript

.json JSON format application/json


Musical Instrument Digital Interface
.mid, .midi audio/midi
(MIDI)
.mpeg MPEG Video video/mpeg

.oga OGG audio audio/ogg

.otf OpenType font font/otf

.png Portable Network Graphics image/png

.pdf Portable Document Format (PDF) application/pdf

.ppt Microsoft PowerPoint application/vnd.ms-powerpoint

.rar RAR archive application/x-rar-compressed

.rtf Rich Text Format (RTF) application/rtf

.sh Bourne shell script application/x-sh

.svg Scalable Vector Graphics (SVG) image/svg+xml

Java Script 119


Nandha Arts and Science College PHP –III Unit BCA Department

Small web format (SWF) OR ADOBE


.swf application/x-shockwave-flash
FLASH FILE
.tar Tape Archive (TAR) application/x-tar

.tif, .tiff Tagged Image File Format (TIFF) image/tiff

.ttf TrueType Font font/ttf

.vsd Microsoft Visio application/vnd.visio

.wav Waveform Audio Format audio/x-wav

.woff Web Open Font Format (WOFF) font/woff

.woff2 Web Open Font Format (WOFF) font/woff2

.xhtml XHTML application/xhtml+xml

.xls Microsoft Excel application/vnd.ms-excel

.xml XML application/xml

.xul XUL application/vnd.mozilla.xul+xml

.zip ZIP archive application/zip

.3gp 3GPP audio/video container Audio/video/3gpp

.3g2 3GPP2 audio/video container Audion/ video/3gpp2

.7z 7-zip archive application/x-7z-compressed

JavaScript: Plug-ins:
 In computing, a plug-in (or plugin, add-in, addin, add-on, or addon) is a software component
that adds a specific feature to an existing computer program. When a program supports plug-
ins, it enables customization.
 A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By
extending the prototype object you enable all jQuery objects to inherit any methods that you
add. As established, whenever you call jQuery() you're creating a new jQuery object, with all
of jQuery's methods inherited.
 The idea of a plugin is to do something with a collection of elements. You could consider each
method that comes with the jQuery core a plugin, like .fadeOut() or .fadeIn ().
 A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery
methods which can be used along with jQuery library methods.

How to use Plugins


To make a plug-in's methods available to us, we include plug-in file very similar to jQuery
library file in the <head> of the document.
We must ensure that it appears after the main jQuery source file, and before our custom
JavaScript code.
Example shows how to include jquery.plug-in.js plugin −
<html>

Java Script 120


Nandha Arts and Science College PHP –III Unit BCA Department

<head>
<title> The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src = "jquery.plug-in.js" type = "text/javascript"> </script>
<script src = "custom.js" type = "text/javascript"> </script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function()
{
.......your custom code.....
});
</script>
</head>
<body>
.............................
</body> </html>

How to develop a Plug-in


This is very simple to write your own plug-in. Following is the syntax to create a method
−jQuery.fn.methodName = methodDefinition;
Here methodName is the name of new method and methodDefinition is actual method
definition.
The guideline recommended by the jQuery team is as follows −
 Any methods or functions you attach must have a semicolon (;) at the end.
 Your method must return the jQuery object, unless explicitly noted otherwise.
 You should use this. Each to iterate over the current set of matched elements - it produces
clean and compatible code that way.
 Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js.
 Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via
noConflict() method.

Plug-ins:- (Ex: XML)


The plug-ins are the components that allow you be extend the browser capabilities.

Interacting with Plug-ins:


The terms extensible applied to browsers such as Netscape Navigator and internet explorer. You can
add for additional features to the browser.
Ex:- if you want to use the MIDI file in some of the browser, that particular browser is not supporting
the MIDI file, you can download a plug-ins for this purpose, then we can play back MIDI sound file.
Java Script 121
Nandha Arts and Science College PHP –III Unit BCA Department

Java script (Plug-in):


• XML • CSS • MIDI file • Audio file • Video file • Flash player, etc.,
Definition:
• A module that is attaches to another program to add additional functionality.
• It Netscape Navigator, plug-ins are allowed movies and animations to be played back certain
kind of movie file can be play or audio to be retrieved in real time.
• You can download the plug-ins within 20 minutes and we can get more capabilities of browser.

What is jQuery?
JavaScript and jQuery are actually the same thing. In a nutshell, jQuery is a set of JavaScript libraries that
have been designed specifically to simplify HTML document traversing, animation, event handling, and Ajax
interactions. Before jQuery was developed, web developers created their own custom frameworks in
JavaScript. This allowed them to work around specific bugs without wasting time debugging common features.
This led to groups of developers creating JavaScript libraries that were open source and free to use.
What is Framework?
A JavaScript framework is an application framework written in JavaScript. It differs from a JavaScript library
in its control flow: a library offers functions to be called by its parent code, whereas a framework defines the
entire application design. A developer does not call a framework; instead it is the framework that will call and
use the code in some particular way. Some JavaScript frameworks follow the model–view–controller paradigm
designed to segregate a web application into orthogonal units to improve code quality and maintainability.
Examples: AngularJS, Ember.js, Meteor.js.

What is AJAX?
AJAX = Asynchronous JavaScript and XML. It is a technique for creating fast and dynamic web pages. It
allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind
the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications: Google Maps, Gmail, Youtube, and Facebook tabs.

What is Angular JS?


 AngularJS is easy to learn.
 AngularJS extends HTML with new attributes,
 AngularJS is perfect for Single Page Applications (SPAs),
 AngularJS is a JavaScript framework written in JavaScript.
 AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
 AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

---x---x---x---

Java Script 122


UNIT-IV

Hypertext Pre Processor


PHP (Hypertext PreProcessor)
 PHP is a server-side scripting language designed for web development but also used as a general-
purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference
implementation is now produced by The PHP Group. PHP originally stood for Personal Home Page,
but it now stands for the recursive acronym PHP: Hypertext Preprocessor.
 PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, Post greSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object architectures (Common Object Model (COM) & Common
Object Request Broker Architecture (CORBA), making n-tier development a possibility for the
first time.
 The standard PHP interpreter, powered by the Zend Engine, is free software released under the
PHP License.
 PHP Syntax it’s like a C.
 Extension of PHP files .php, .phtml, .php3, .php4, .php5, .php7, .phps, .php-s, .pht, .phar
 Apache as the base server for hosting PHP MySQL applications, Best Open Source PHP Web Servers
1. XAMPP It is one of the most commonly used open source PHP servers
2. WAMP It is another open source PHP server for hosting web apps best alternative to XAMPP.
3. LAMP Developed particularly for Linux operating systems
4. LEMP LEMP stack is a popular alternative for the LAMP users, & has almost same functionalities
5. MAMP MAC operating systems, its acronym stands for MAC, Apache, MySQL & PHP.
6. AMPPS Combination of WAMP, LAMP and MAMP stacks.
7. WPN-XM It’s only supports Windows operating system
8. EasyPHP This is only one great web server tool
 Current Version 7.3 Released: 6 December 2018.
Latest Version PHP 7.3.7 Released: - July 4, 2019
Nandha Arts and Science College PHP –IV Unit BCA Department

Common uses of PHP:


 PHP performs system functions, i.e. from files on a system it can create, open, read, write & close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
 You add, delete and modify elements within your database thru PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.

5 Characteristics of PHP (Already u know HTML, CSS, JavaScript etc.,)

• Simplicity • Efficiency • Security • Flexibility • Familiarity

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, & the result is returned to the browser as plain HTML.
 PHP files have extension ".php, .phtml, .php3, .php4, .php5, .php7, .phps, .php-s, .pht, .phar”
What can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, 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 restrict users to access some pages on your website
 PHP can encrypt data with PHP you are not limited to output HTML. You can output images,
PDF files, and even flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
 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, download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
PHP Editors
PHP IDE is a PHP Integrated Development Environment for developing, debugging and managing PHP
files. These are few best PHP IDE's & Editors that I've using…
1. NetBeans IDE 2. Eclipse PDT 3. Aptana Studio 4. PHP Designer
5. Notepad++ 6. Sublime Text 7. Atom 8. PhpStorm
9. Visual Studio Code - Open Source 10. Zend Studio

PHP (Hypertext PreProcessor)


124
Nandha Arts and Science College PHP –IV Unit BCA Department
Net Beans IDE Editor

Advantages of PHP over Other Languages


If you're familiar with other server-side languages like ASP.NET or Java, you might be wondering what
makes PHP so special. There are several advantages why one should choose PHP.
• Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web
development, PHP is often considered as the preferable choice of language to learn.
• Open source: PHP is an open-source project. It is developed and maintained by a worldwide
community of developers who make its source code freely available to download and use.
• Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is
compatible with almost all servers used today such Apache, IIS, etc.
• Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other
scripting languages like ASP, Ruby, Python, Java, etc.
• Vast Community: Since PHP is supported by the worldwide community, finding help or
documentation related to PHP online is extremely easy.

PHP Syntax(Basic):
 A PHP script can be placed anywhere in the document.
 A PHP script starts 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:

PHP (Hypertext PreProcessor)


125
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 105
<html>
My First PHP
<body>
<h1> My first PHP page</h1>
page
<?php Hello World
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements are terminated by semicolon (;).
The closing tag of a block of PHP code also automatically implies a semicolon.

Example – 106
Echo Example Program
<html> Hello by PHP echo this is multi line text printed by PHP echo statement
<body>
<h1> Echo Example Program </h1>
<?php
echo "Hello by PHP echo
this is multi line
text printed by
Echo Example Program
Message is:
PHP echo statement
Hello! I am Learn in PHP Language
";
?> </body> </html>

Example – 107
<html> <body> <h2> Echo Example Program </h1>
<?php
$msg="Hello! I am Learn in PHP Language";
echo "Message is: $msg";
?> </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 editing the code!
 Comments let other programmers understand what you were doing in each step
 To remind yourself what you did - Most programmers have experienced coming back to their own
work a year or two later and having to re-figure out what they did.
 Comments can remind you of what you were thinking when you wrote the code.
 PHP supports three ways of commenting.

PHP (Hypertext PreProcessor)


126
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 108
<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 more than one line */
?> </body> </html>
PHP Case Sensitivity:
▪ In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are case-insensitive.
▪ In the example below, all three echo statements below are legal (and equal):

Example – 109
Hello World!
<html> <body> Programmer
follow in this Hello World!
<?php
method only
Hello World!
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?> </body> </html>

TYPES: PHP supports eight primitive types.

Four scalar types: • Boolean • integer • float • string


Two compound types: • array • object
and finally two special types: • resource • NULL
This manual also introduces some pseudo-types for readability reasons:
• mixed • number • callback

PHP (Hypertext PreProcessor)


127
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP Variables:
Variables are "containers" for storing information
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic (basic) types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
PHP has a total of eight data types which we use to construct our variables:
 Integers: are whole numbers, without a decimal point, like 4195.
 Doubles: are floating-point numbers, like 3.14159 or 49.1.
 Booleans: have only two possible values either true or false.
 NULL: is a special type that only has one value: NULL.
 Strings: are sequences of characters, like 'PHP supports string operations.'
 Arrays: are named and indexed collections of other values.
 Objects: are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
 Resources: are special variables that hold references to resources external to PHP
 The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type.

<?php
$a="hello"; //letter (valid)
hello
$_b="hello"; //underscore (valid) hello
echo "$a <br/> $_b";
?>
Example – 110
<?php Much like Algebra
$x=5; x = 5 11
$y=6; (or) y = 6
$z=$x+$y; z = x+y
echo $z;
?>

PHP (Hypertext PreProcessor)


128
Nandha Arts and Science College PHP –IV Unit BCA Department

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, 09,a-z, & _ )
 Variable names are case sensitive ($y and $Y are two different variables)

Example – 111
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
PHP is a Loosely Type Language:
 PHP automatically converts the variable to the correct data type, depending on its value.
 In other languages such as C, C++, and Java, the programmer must declare the name and
type of the variable before using it.
PHP Variables Scope:
 In PHP, variables can be declared anywhere in the script.
 The scope of a variable is the part of the script where the variable can be referenced/used.
 PHP has three different variable scopes:
-> Local -> Global -> Static -> Function parameters

Local Variables
A variable declared in a function is considered local; that is, it can be referenced only in that function.

Example – 112
$x inside function is 0.
<?
$x outside of function is 4.
$x = 4;
function assign x ()
{
$x = 0;
print "\$x inside function is
$x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>

PHP (Hypertext PreProcessor)


129
Nandha Arts and Science College PHP –IV Unit BCA Department

Global Variables
In contrast to local variables, a global variable can be accessed in any part of the program. However,
in order to be modified, a global variable must be explicitly declared to be global in the function in
which it is to be modified. This is accomplished, conveniently enough, by placing the keyword
GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of
an already existing variable tells PHP to use the variable having that name. Consider an example:

Example – 113
Somevar is 16
<?
$somevar = 15;
function addit()
{
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
} Test variables inside the function:
addit();
E_NOTICE : type 8 -- Undefined variable: x -- at line 8
?> Variable x is:
Variable y is: 10
Example – 114
Test variables outside the function:
<?php
Variable x is: 5
$x=5; Variable y is: 5
$y=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y"; ?>

PHP (Hypertext PreProcessor)


130
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP The global Keyword:


• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function):

Example – 115
<?php
$x=5;
$y=10;
function myTest()
{ Output
global $x,$y; 15
$y=$x+$y;
}
myTest();
echo $y;
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of
the variable. This array is also accessible from within functions and can be used to update global
variables directly.

Example – 116
<?php Output
$x=5;
$y=20; 25
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
PHP the static Keyword:
▪ Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
▪ To do this, use the static keyword when you first declare the variable:
▪ The variables declared as function parameters, which are destroyed on the function's exit, a
static variable will not lose its value when the function exits and will still hold that value should
the function be called again.
▪ You can declare a variable to be static simply by placing the keyword static in front of the
variable name.

PHP (Hypertext PreProcessor)


131
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 117
<?php
function myTest()
{
static $x=0; Output
echo $x;
$x++; 0
} 1
myTest(); 3
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it.
Note: The variable is still local to the function.

PHP echo and print Statements:


In PHP there is two basic ways to get output: echo and print.
There are some differences between echo and print:
✓ echo - can output one or more strings
✓ print - can only output one string, and returns always 1
Tip: echo is marginally faster compared to print as echo does not return any value.

The PHP echo Statement


 The echo statement can output one or more strings. In general terms, the echo statement can
display anything that can be displayed to the browser, such as string, numbers, variables
values, the results of expressions etc.
 Echo is a language construct, and can be used with or without parentheses: echo or echo().
However, if you want to pass more than one parameter to echo, the parameters must not
be enclosed within parentheses.
Display Strings
The following example shows how to display different strings with the echo command (also notice that
the strings can contain HTML markup):
PHP is fun!
Example – 118 Hello world!
I'm about to learn PHP!
<?php This string was made
with multiple
echo "<h2>PHP is fun!</h2>"; parameters.
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This"," string"," was"," made", "with multiple parameters.";
?>

PHP (Hypertext PreProcessor)


132
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 119 (Display String Variable with the echo command)


<?php
$txt1="Learn PHP";
$txt2="phplearn.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
Learn PHP
echo "<br>"; Study PHP at phplearn.com
echo "Study PHP at $txt2";
My car is a Volvo
echo "<br>";
echo "My car is a {$cars[0]}";
?>
The PHP print Statement
 Print is also a language construct, and can be used with or without parentheses: print or
print().
 The print statement (an alternative to echo) to display output to the browser. Like echo the
print is also a language construct not a real function. So you can also use it without
parentheses like: print or print().
 The print statement can only output one string, and always returns 1.

Example – 120 (Display different String Variable with the echo command)
<?php PHP is fun
print "<h2>PHP is fun!</h2>";
Hello world
print "Hello world!<br>";
print "I'm about to learn PHP!"; I’m about to learn PHP
?>

Example – 121 (Display String Variables with the echo command)


<?php
$txt1="Learn PHP"; Learn PHP
$txt2="phplearn.com";
Study PHP at phplearn.com
$cars=array("Volvo","BMW","Toyota");
MY Car is a BMW
print $txt1;
print "<br>";
print "Study PHP at $txt2";
print "<br>";
print "My car is a {$cars[1]}";
?>

PHP (Hypertext PreProcessor)


133
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP Data Types:


String, Integer, Floating point numbers, Boolean, Array, Object, NULL.
PHP Strings
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:

Example – 122
<?php
Hello world!
$x = "Hello world!";
echo $x; Hello Friends!

echo "<br>";
$x = 'Hello Friends!';
echo $x;
?>
PHP Integers
An integer is a number without decimals.
Rules for integers:
• An integer must have at least one digit (0-9)
• An integer cannot contain comma or blanks
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16- based -
prefixed with 0x) or octal (8-based - prefixed with 0)
The PHP var_dump() function returns the data type and value of variables:

Example – 123
<?php $x = 5985;
int(5985)
var_dump($x); int(-345)
echo "<br>"; int(140)
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
“var_dump” function, which limits the
var_dump($x);
output and prints the file path and line
echo "<br>";
of the invocation.
$x = 047; // octal number var_dump($x);
?>

PHP (Hypertext PreProcessor)


134
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP Floating Point Numbers


• A floating point number is a number with a decimal point or a number in exponential form.
• In the following example we will test different numbers. The PHP var_dump() function
returns the data type and value of variables:

Example – 124
<?php $x = 10.365;
var_dump($x); echo "<br>";
$x = 2.4e3; float(10.365)
var_dump($x); echo "<br>"; float(2400)
$x = 8E-5; float(8.0E-5)
var_dump($x);
?>
PHP Booleans
Booleans can be either TRUE or FALSE.
$x=true; $y=false;
Booleans are often used in conditional testing.
PHP NULL Value
• The special NULL value represents that a variable has no value. NULL is the only possible
value of data type NULL.
• The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.
• Variables can be emptied by setting the value to NULL:

Example – 125
<?php
$x="Hello world!";
$x=null; null
var_dump($x);
?>
PHP 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. The value cannot be changed during the script.
 A valid constant name starts with a letter or underscore (no $ sign before the constant name).
 To define a constant you have to use define() function and to retrieve the value of a constant, you have
to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can
also use the function constant() to read a constant's value if you wish to obtain the constant's name
dynamically.

Note: Unlike variables, constants are automatically global across the entire script.

PHP (Hypertext PreProcessor)


135
Nandha Arts and Science College PHP –IV Unit BCA Department

constant() function
 As indicated by the name, this function will return the value of the constant.
 This is useful when you want to retrieve value of a constant, but you do not know its name, i.e.,
it is stored in a variable or returned by a function.

Example – 126
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line 5050
?>
Only scalar data (boolean, integer, float and string) can be contained in
constants.

Differences between constants and variables are


• There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be defined using the define() function.
• Constants may be defined and accessed anywhere without regard to variable scoping rules.
• Once the Constants have been set, may not be redefined or undefined.
Set a PHP Constant
To set a constant, use the define() function - it takes three parameters: The first parameter defines
the name of the constant, the second parameter defines the value of the constant, and the optional
third parameter specifies whether the constant name should be case-insensitive. Default is false.

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

echo GREETING;
?>

Expressions:
 In PHP there are two types of expression for us to look at. One is something called a "regular
expression", which is used in the manipulation of text. The other is more mathematical in
nature, expressing operations to be performed on values and variables. Here's a simple
example: c = a + b
 Assuming a and b are numbers (remember data types? -- the result would be different if
they were strings -- more about that later) this expression would add a and b and put the
sum into c. In the expression a + b the plus sign is an arithmetic operator.
 Expressions are the most important building stones of PHP. In PHP, almost anything you write

PHP (Hypertext PreProcessor)


136
Nandha Arts and Science College PHP –IV Unit BCA Department

is an expression. The simplest yet most accurate way to define an expression is "anything
that has a value".
 The most basic forms of expressions are constants and variables. When you type "$a = 5",
you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an
expression with the value of 5 (in this case, '5' is an integer constant).
 After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd
expect it to behave just as if you wrote $b = 5.
 In other words, $a is an expression with the value of 5 as well. If everything works right, this
is exactly what will happen.

Example – 128
<?php
function foo()
{
return 5;
}
?>
PHP Operators:
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5
are called operands and + is called operator. PHP language supports following type of operators.
• Arithmetic Operators • Comparison Operators
• Logical (or Relational) Operators • Assignment Operators
• Conditional (or Ternary) Operators

Arithmetic Operators Assume variable A holds 10 and variable B holds 20 then:


Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide the numerator by denominator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

PHP (Hypertext PreProcessor)


137
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 129
<html>
<head>
<title>Arithmetical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addition Operation Result: $c <br/>";
$c = $a - $b;
echo "Subtraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html>

Addition Operation Result: 62


Subtraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1
Modulus Operation Result: 2
Increment Operation Result: 42
Decrement Operation Result: 4

PHP (Hypertext PreProcessor)


138
Nandha Arts and Science College PHP –IV Unit BCA Department

Comparison Operators Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


== Checks if the value of two operands are equal or not, if yes,
then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values
are not equal, then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of
right operand, if yes, then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of
right operand, if yes, then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to
the value of right operand, if yes then condition becomes (A >= B) is not true.
true.
<= Checks if the value of left operand is less than or equal to the
value of right operand, if yes, then condition becomes true. (A <= B) is true.
=== i ) Check variable values ii) Data type (A === B) is true.

<> Not equal (A<>B) is true


Example – 130
<html> <head> <title>Comparison Operators</title><head>
<body> <?php $a = 42; $b = 20;
if( $a == $b ){
echo "TEST1 : a is equal to b<br/>";
}else{
echo "TEST1 : a is not equal to b<br/>";}
if( $a > $b ){
echo "TEST2 : a is greater than b<br/>";
}else{
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ){
echo "TEST3 : a is less than b<br/>";
}else{
echo "TEST3 : a is not less than b<br/>";
}
if( $a != $b ){
echo "TEST4 : a is not equal to b<br/>";
}else{
echo "TEST4 : a is equal to b<br/>";

PHP (Hypertext PreProcessor)


139
Nandha Arts and Science College PHP –IV Unit BCA Department

}
if( $a >= $b ){
echo "TEST5 : a is either greater than or equal to b<br/>";
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>

TEST1 : a is not equal to b


TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b

Logical Operators
The following logical operators are supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


and Called Logical AND operator. If both the operands are true, (A and B) is true.
then condition becomes true.
or Called Logical OR Operator. If any of the two operands are non (A or B) is true.
zero, then condition becomes true.

&& Called Logical AND operator. If both the operands are non zero, (A && B) is true.
then condition becomes true.
|| Called Logical OR Operator. If any of the two operands are non (A || B) is true.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is false.
its operand. If a condition is true, then Logical NOT operator will
make false.

PHP (Hypertext PreProcessor)


140
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 131
<html>
<head><title>Logical Operators</title></head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ) {
echo "TEST1 : Both a and b are true<br/>";
} else{
echo "TEST1 : Either a or b is false<br/>";
}if( $a and $b ){
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
} if( $a || $b ){
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}if( $a or $b ){
echo "TEST4 : Either a or b is true<br/>";
}else{
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10; $b = 20;
if( $a ){
echo "TEST5 : a is true <br/>";
}else{
TEST1 : Either a or b is false
echo "TEST5 : a is false<br/>"; TEST2 : Either a or b is false
TEST3 : Either a or b is true
}if( $b ){
TEST4 : Either a or b is true
echo "TEST6 : b is true <br/>"; TEST5 : a is true
}else{ TEST6 : b is true
TEST7 : a is false
echo "TEST6 : b is false<br/>";
TEST8 : b is false
}if( !$a ){
echo "TEST7 : a is true <br/>";
}else{
echo "TEST7 : a is false<br/>";

PHP (Hypertext PreProcessor)


141
Nandha Arts and Science College PHP –IV Unit BCA Department

}if( !$b ){
echo "TEST8 : b is true <br/>";
}else{
echo "TEST8 : b is false<br/>";
}
?> </body> </html>

Assignment Operators PHP supports the following assignment operators:

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left C = A + B will assign the value of A + B
side operand into C
+= Add AND assignment operator, It adds right operand to the left operand and C += A is equivalent to
assign the result to left operand

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is equivalent to C=C-A
operand and assign the result to left operand
*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is equivalent to C = C*A
operand and assign the result to left operand

/= Divide AND assignment operator, It divides left operand with the right operand C /= A is equivalent to C= C / A
and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand

Example – 132
<html> <head><title>Assignment Operators</title></head>
<body> <?php
$a = 42; $b = 20;
$c = $a + $b; /* Assignment operator */
echo "Addition Operation Result: $c <br/>";
$c += $a; /* c value was 42 + 20 = 62 */
echo "Add AND Assignment Operation Result: $c <br/>";
$c -= $a; /* c value was 42 + 20 + 42 = 104 */
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?> </body> </html>

PHP (Hypertext PreProcessor)


142
Nandha Arts and Science College PHP –IV Unit BCA Department

Addition Operation Result: 62


Add AND Assignment Operation Result: 104
Subtract AND Assignment Operation Result: 62
Multiply AND Assignment Operation Result: 2604
Division AND Assignment Operation Result: 62
Modulus AND Assignment Operation Result: 20

Conditional Operator
There is one more operator called the conditional operator. It first evaluates an expression for a true
or false value and then executes one of the two given statements depending upon the result of
the evaluation.

Operator Description Example

?: Conditional Expression If Condition is true? Then value X : Otherwise value Y

Example – 133
<html>
<head><title>Arithmetical Operators</title><head>
<body>
TEST1 : Value of result is 20
<?php
TEST2 : Value of result is 10
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?> </body> </html>

Operators Categories
All the operators we have discussed above can be categorized into the following categories:
• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.
• The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first expression.
• Assignment operators, which assign a value to a variable.

PHP (Hypertext PreProcessor)


143
Nandha Arts and Science College PHP –IV Unit BCA Department

Precedence(Priority) of PHP Operators


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then adds into 7. Here operators with the highest
precedence appear at the top of the table, those with the lowest appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.

Category Operator Associativity


Unary ! ++ -- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left
PHP String Operators
Operator Name Example Result
$txt1 = "Hello" Now $txt2 contains
. Concatenation
$txt2 = $txt1 ." world!" "Hello world!"
Concatenation $txt1 = "Hello" Now $txt1 contains
.= assignment $txt1 .= " world!" "Hello world!"

Example – 134
<?php
$a = "Hello";
$b = $a."world!";
Helloworld! Helloworld!
echo $b;
$x="Hello";
$x.="world!";
echo $x;
?>

PHP (Hypertext PreProcessor)


144
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP Control Structures:


 Any PHP script is built out of a series of statements. A statement can be an Assignment, a
function call, a loop, a conditional statement of even a statement that does nothing (an empty
statement).
 Statements usually end with a semicolon. In addition, statements can be grouped into a
statement-group by encapsulating a group of statements with curly braces. A statement-
group is a statement by itself as well.
1) If Statement 2) if….else Statement
3) Elseif Statement 4) Switch Statement If Statement

If Statement
 An if statement is a way of controlling the execution of a statement that follows it (that is, a
single statement or a block of code inside braces).
 The if statement evaluates an expression between parentheses. If this expression results in a
true value, the statement is executed.
 Otherwise, the statement is skipped entirely. This enables scripts to make decisions based on
any number of factors:
Syntax:-
if ( expression )
{
Statement; or code to be executed if condition is true;
}
Example – 135 The following code would display a is bigger than b if $a is bigger than $b:
<?php
$a=10; $b=5;
if ($a > $b) A is bigger than B
{
echo "A is bigger than B";
} ?>

Else Statement:
• When working with the if statement, you will often want to define an alternative block of code
that should be executed if the expression you are testing evaluates to false.
• You can do this by adding else to the if statement followed by a further block of code:

PHP (Hypertext PreProcessor)


145
Nandha Arts and Science College PHP –IV Unit BCA Department

Syntax:-
if ( expression ) if (condition)
{
Statement; code to be executed if condition is true;
} (Or)
else else
{
code to be executed if condition is false;
Statement;
}
Example – 136 the following code would

display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:

<?php
$a=10; $b=15;
if ($a > $b) {
echo "A is bigger than B"; B is bigger than A
}
else {
echo "B is bigger than A";
} ?>
If..Else..if Statement (or) Nested if Statement
 As its name suggests, is a combination of if and else. Like else, it extends an if statement to
execute a different statement in case the original if expression evaluates to FALSE.
 However, unlike else, it will execute that alternative expression only if the elseif conditional
expression evaluates to TRUE.
Syntax:-
if ( expression )
{
Statement; if (condition)
}
code to be executed if condition is true;
elseif
{ Or elseif (condition)
Statement;
} code to be executed if condition is true;
else
{ else
Statement
} code to be executed if condition is false;
Example – 137
<?php $a=10; $b=10;
if ($a > $b){ A and B are equal
echo "A is bigger than B"; }
elseif ($b > $a) {
echo " B is bigger than A "; }
else {
echo "A and B are equal";
} ?>

PHP (Hypertext PreProcessor)


146
Nandha Arts and Science College PHP –IV Unit BCA Department

Switch Statement:
 The switch statement is similar to a series of IF statements on the same expression.
 In many occasions, you may want to compare the same variable (or expression) with many
different values, and execute a different piece of code depending on which value it equals to.
Syntax:-
switch (expression)
{
case label 1:
code to be executed if expression = label1;
break;
case label 2:
code to be executed if expression = label2;
break;
default:
code to be executed
}
Example – 138
<html>
<body>
<?php
$d=date("D"); Today is Sunday
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
} ?> </body> </html>

PHP (Hypertext PreProcessor)


147
Nandha Arts and Science College PHP –IV Unit BCA Department

PHP Loops:
Loops in PHP are used to execute the same block of code a specified number of times.
In PHP, we have the following looping statements:
for - loops through a block of code a specified number of times.
while - loops through a block of code if and as long as a specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long as a special
condition is true.
foreach - loops through a block of code for each element in an array.

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition is true)
{
code to be executed;
}

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

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 is true);

PHP (Hypertext PreProcessor)


148
Nandha Arts and Science College PHP –IV Unit BCA Department

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

PHP for Loops:


PHP for loops execute a block of code a specified number of times.
Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}
(OR)
<?php
for (initialize; condition; increment) {
//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:
The number is: 0
Example – 141 The number is: 1
The number is: 2
<?php The number is: 3
for($x=0; $x<=10; $x++) The number is: 4
The number is: 5
{ The number is: 6
echo "The number is: $x <br>"; The number is: 7
The number is: 8
} The number is: 9
?> The number is: 10

PHP (Hypertext PreProcessor)


149
Nandha Arts and Science College PHP –IV Unit BCA Department

The PHP foreach Loop


The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next element
will be processed.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

Example – 142
Value is 1
<html>
Value is 2
<body> Value is 3
<?php Value is 4
Value is 5
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Example – 143
<html>
<body>
<?php
$array = array( 'A','B','C','D','E'); Value is A
Value is B
foreach( $array as $value )
Value is C
{ Value is D
echo "Value is $value <br />"; Value is E
}
?>
</body>
</html>

PHP (Hypertext PreProcessor)


150
Nandha Arts and Science College PHP –IV Unit BCA Department

The break statement


The PHP break keyword is used to terminate the execution of a
loop prematurely (early). The break statement is situated inside the
statement block. If gives you full control and whenever you want to
exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed

Example – 144 The condition test becomes true when the

counter value reaches 3 and loop terminates.


<html> <body> <?php
$i = 0;
while( $i < 10)
Loop stopped at i = 3
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?> </body> </html>

The Continue Statement


The PHP continue keyword is used to halt the current
iteration of a loop but it does not terminate the loop. Just
like the break statement the continue statement is situated
inside the statement block containing the code that the loop
executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is
skipped and next pass starts.

Example – 145
<html> <body> <?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
Value is 1
{ Value is 2
Value is 4
if( $value == 3 )
Value is 5
continue;
echo "Value is $value <br />";
}
?> </body> </html>

PHP (Hypertext PreProcessor)


151
Nandha Arts and Science College PHP –IV Unit BCA Department

Array
An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define
an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID which is called
array index.
1. Numeric array or Indexed array - An array with a numeric index. Values are stored and accessed
in linear fashion.
2. Associative array - An array with strings as index. This store element values in association with
key values rather than in a strict linear index order.
3. Multidimensional array - An array containing one or more arrays and values are accessed using
multiple indices NOTE: Built-in array functions is given in function reference PHP Array Functions
There are two ways to define Numeric or indexed array:
1st way: $season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter"; Season are: summer,
$season[2]="spring"; winter, spring, autumn
$season[3]="autumn";

Example – 146
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>

Example – 147
<?php Season are: summer,
$season[0]="summer"; winter, spring and
$season[1]="winter"; autumn
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default, the array index starts from zero.

PHP (Hypertext PreProcessor)


152
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 148
<html>
<body>
<?php
/* First method to create array. */
Value is 1
$numbers = array( 1, 2, 3, 4, 5); Value is 2
Value is 3
foreach( $numbers as $value ) Value is 4
Value is 5
{ Value is one
Value is two
echo "Value is $value <br />"; Value is three
Value is four
} Value is five
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?> </body> </html>

Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different
in terms of their index. Associative array will have their index as string so that you can establish a
strong association between key and values. To store the salaries of employees in an array, a
numerically indexed array would not be the best choice. Instead, we could use the employees names
as the keys in our associative array, and the value would be their respective salary.
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sumathi"=>"350000","Raja"=>"450000","Karthik"=>"600000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";

PHP (Hypertext PreProcessor)


153
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 149
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Raja"=>50000,"Sumathi"=>35000,"Banu"=>25000);
echo "Salary of Raja is ".$salaries['Raja']. "<br />";
echo "Salary of Sumathi is ".$salaries['Sumathi']. "<br />";
echo "Salary of Banu is ".$salaries['Banu']. "<br />";
/* Second method to create array. */
$salaries['Raja'] = "high";
Salary of Raja is 50000
$salaries['Sumathi'] = "medium"; Salary of Sumathi is 35000
$salaries['Banu'] = "low"; Salary of Banu is 25000
echo "Salary of Raja is Salary of Raja is high
Salary of Sumathi is medium
".$salaries['Raja']. "<br />";
Salary of Banu is low
echo "Salary of Sumathi is
".$salaries['Sumathi']. "<br />";
echo "Salary of Banu is ".$salaries['Banu']. "<br />";
?>
</body>
</html>

Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using
multiple index.
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.
Definition
$emp = array
(
array(1,"sumathi",400000),
array(2,"raja",500000),
array(3,"rahul",300000)
);

PHP (Hypertext PreProcessor)


154
Nandha Arts and Science College PHP –IV Unit BCA Department

Example – 150 Create a two-dimensional array to store marks of three students in three subjects:
<html>
<body>
<?php
$marks = array(
"Raja" => array ("physics" => 95, "maths" => 90, "chemistry" => 89),
"Sumathi" => array ( "physics" => 30, "maths" => 92, "chemistry" => 29),
"Banu" => array("physics" => 31, "maths" => 22, "chemistry" => 89 ) );
/* Accessing multi-dimensional array values */
echo "Marks for Raja in physics : " ;
echo $marks['Raja']['physics'] . "<br />";
echo "Marks for Sumathi in maths : ";
echo $marks['Sumathi']['maths'] . "<br />";
echo "Marks for Banu in chemistry : " ;
echo $marks['Banu']['chemistry'] . "<br />";
?>
</body>
</html> Marks for Raja in physics : 95
Marks for Sumathi in maths : 92
Marks for Banu in chemistry : 89

---x---x---x---

PHP (Hypertext PreProcessor)


155
UNIT-V

Hypertext Pre Processor


PHP-Functions
 Besides the built-in PHP functions, we can create our own functions.
 A function is a block of statements that can be used repeatedly in a program.
 A function will not execute immediately when a page load.
 A function will be executed by a call to the function.
 A function accepts values from you, processes them, and then performs an action returns a
new value, or both.
 A function is a self-contained block of code that can be called by your scripts. When called,
the function's code is executed.
PHP provides us with two major types of functions:
 Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), fread(), gettype() and so on.
 User Defined Functions: Apart from the built-in functions, PHP allows us to create our own
customised functions called the user-defined functions. Using this we can create our own
packages of code and use it wherever necessary by simply calling it.

Why should we use functions?


 Reusability: If we have a common code that we would like to use at various parts of a program,
we can simply contain it within a function and call it whenever required. This reduces the time
and effort of repetition of a single code. This can be done both within a program and also by
importing the PHP file, containing the function, in some other program.
 Easier error detection: Since, our code is divided into functions, we can easily detect in which
function, the error could lie and fix them fast and easily.
 Easily maintained: As we have used functions in our program, so if anything or any line of
code needs to be changed, we can easily change it inside the function and the change will be
reflected everywhere, where the function is called. Hence, easy to maintain.
Nandha Arts and Science College PHP – V Unit BCA Department

Creating a Function
While creating a user defined function we need to keep few things in mind:
 Any name ending with an open and closed parenthesis is a function.
 A function name always begins with the keyword function.
 To call a function we just need to write its name followed by the parenthesis
 A function name cannot start with a number. It can start with an alphabet or underscore.
 A function name is not case-sensitive.
 You can pass values to functions, which will then work with them. When finished, a function
can pass a value back to the calling code.
1. Creating PHP Functions 3. Calling PHP Functions
2. Use Parameters - Functions 4. Returning Values - Functions Creating PHP Functions:
Syntax:
function function_name()
{
executable code;
}

1. Creating PHP Function


It is very easy to create your own PHP function. Suppose you want to create a PHP function which
will simply write a simple message on your browser when you will call it.
Example creates a function called writeMessage() and then calls it just after creating it.

Example – 151 You are really a nice person,


<html> Have a nice time!
<head>
<title> Writing PHP Function </title>
</head>
<body>
<?php
function writeMessage()/* Defining a PHP Function */
{
echo "You are really a nice person, Have a nice time!";
}
writeMessage(); /* Calling a PHP Function */
?> </body> </html>

PHP (Hypertext PreProcessor) P a g e 157 |


Nandha Arts and Science College PHP – V Unit BCA Department

Calling Your Functions:


Now that you have completed coding your PHP function, it's time to put it through a test run. Below
is a simple PHP script. Let's do two things: add the function code to it and use the function twice.
Example
<?php
bighello();
?>

2. Use Parameters - Functions:


If we were to use parameters, then we would be able to add some extra functionality! A parameter
appears with the parentheses "( )" and looks just like a normal PHP variable.

Example – 152
<?php
function bighello($firstName)
{ Raj
echo "Hello ". $firstName . "!";
}
bighello('Raj');
?>

PHP Functions with Parameters


PHP gives you option to pass your parameters inside a function. You can pass as many as parameters
your like. These parameters work like variables inside your function. The following example takes two
integer parameters and adds them together and then prints them.

Example – 153
<html> <head>
<title> Writing PHP Function with Parameters</title> </head>
<body> <?php
Sum of the two numbers
function addfunction($num1, $num2) is : 30
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunction(10, 20);
?> </body> </html>

PHP (Hypertext PreProcessor) P a g e 158 |


Nandha Arts and Science College PHP – V Unit BCA Department

Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference to the variable
is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You
can pass an argument by reference by adding an ampersand to the variable name in either the
function call or the function definition.
Example – 154
<html>
<head>
<title> Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{ Original Value is 10
$num += 5; Original Value is 16
}
function addSix(&$num)
{
$num += 6;
}
$originalvalue = 10;
addFive( &$ originalvalue );
echo "Original Value is $ originalvalue <br />";
addSix( $ originalvalue );
echo "Original Value is $ originalvalue <br />";
?>
</body>
</html>

4. PHP Functions returning value


A function can return a value using the return statement in conjunction with a value or object. Return
stops the execution of the function and sends the value back to the calling code.

PHP (Hypertext PreProcessor) P a g e 159 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 155
<html>
<head>
<title> Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) Returned value from the
{
function : 50
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(25, 25);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it. The following
function prints NULL in case use does not pass any value to this function.

Example – 156
<html>
<head>
<title> Writing PHP Function which returns value</title>
</head>
<body>
<?php
This is test
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>

PHP (Hypertext PreProcessor) P a g e 160 |


Nandha Arts and Science College PHP – V Unit BCA Department

Object Oriented Concepts


❖ Class: This is a programmer-defined datatype, which includes local functions as
well as local data. You can think of a class as a template for making many
instances of the same kind (or class) of object.
❖ Object: An individual instance of the data structure defined by a class. You define a
class once and then make many objects that belong to it. Objects are also
known as instance.
❖ Member Variable: These are the variables defined inside a class. This data will be invisible to
the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
❖ Member function: These are the function defined inside a class and are used to access object data.
❖ Inheritance: When a class is defined by inheriting existing function of a parent class, then
it is called inheritance. Here child class will inherit all or few member
functions and variables of a parent class.
❖ Parent class: A class that is inherited from by another class. This is also called a base class or super
class.
❖ Child Class: A class that inherits from another class. This is also called a subclass or derived class.
❖ Polymorphism: This is an object oriented concept where the same function can be used for
different purposes. For example, function name will remain same but it may
take different number of arguments and can do different task.
❖ Overloading: a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly,
functions can also be overloaded with different implementation.
❖ Data Abstraction: Any representation of data in which the implementation details are hidden
(abstracted).
❖ Encapsulation: refers to a concept where we encapsulate all the data and member functions
together to form an object.
❖ Constructor: refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
❖ Destructors: refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope.

PHP (Hypertext PreProcessor) P a g e 161 |


Nandha Arts and Science College PHP – V Unit BCA Department

Class and Objects


Define Class
 Classes are the blueprints of objects. One of the big differences between functions and classes is that a
class contains both data (variables) and functions that form a package called an: ‘object’.
 Class is a programmer-defined data type, which includes local methods and local variables.
 Class is a collection of objects. Object has properties and behaviour.
Syntax: We define our own class by starting with the keyword ‘class’ followed by the name you want to give your new class.
<?php
class phpclassname
{
}
?>
(OR)
<?php
class phpClass
{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2)
{
[..]
}
[..]
}
?>
Here is the description of each line:
❖ The special form class, followed by the name of the class that you want to define.
❖ A set of braces enclosing any number of variable declarations and function definitions.
❖ Variable declarations start with the special form var, which is followed by a conventional $
variable name; they may also have an initial assignment to a constant value.
❖ Function definitions look much like standalone PHP functions but are local to the class and
will be used to set and access object data.
Example – 157
<?php
class Books
{
public function name()
{
echo “PHP book”;
}
public function price()
{
echo “Rs. 500/-”;
}
} To create php object we have to use a new operator. Here php object is the object of the Books Class.
$obj = new Books();
$obj->name();
$obj->price();
?>

PHP (Hypertext PreProcessor) P a g e 162 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 158
<?php
class Books
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
function setTitle($par)
{
$this->title = $par;
}
function getTitle()
{
echo $this->title ." <br/>";
}
}
?> The variable $ this is a special variable and it refers to the same object, i.e., itself.

Define Object
An Object is an individual instance of the data structure defined by a class. We define a class once and
then make many objects that belong to it. Objects are also known as instances. Once you defined your
class, then you can create as many objects as you like of that class type.
class Book
{
// Members of class Book
}
// Creating three objects of book
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object. One
member function will be able to process member variable of related object only. Following example
shows how to set title and prices for the three books by calling member functions.

PHP (Hypertext PreProcessor) P a g e 163 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 159
<?php
class Mobile
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
function setName($par)
{
$this->title = $par;
}
function getName()
{
echo $this->title ." <br/>";
}
}
$Samsung = new Mobile();
$Xiaomi = new Mobile();
$Iphone = new Mobile();
$Samsung->setName( "SamsungS8 );
$Iphone->setName( "Iphone7s" );
$Xiaomi->setName( "MI4" );
$Samsung->setPrice( 90000 ); Samsung S8
$Iphone->setPrice( 95000 ); Iphone S7
$Xiaomi->setPrice( 15000 ); MI4
$Samsung->getName();
90000
$Iphone->getName();
95000
$Xiaomi->getName();
$Samsung->getPrice(); 15000
$Iphone->getPrice();
$Xiaomi->getPrice();
?>

PHP (Hypertext PreProcessor) P a g e 164 |


Nandha Arts and Science College PHP – V Unit BCA Department

Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may
be accessed in three possible situations:
• From outside the class in which it is declared
• From within the class in which it is declared
• From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the
members of a class, then you define class members as private or protected.

Example – 160
<?php
// Define MyClass
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

//Define MyClass2
class MyClass2 extends MyClass
{
// We can redeclare the public and protected properties, but not private
public $public = 'Public2';
protected $protected = 'Protected2';

PHP (Hypertext PreProcessor) P a g e 165 |


Nandha Arts and Science College PHP – V Unit BCA Department

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj2 = new MyClass2();


echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public2, Protected2, Undefined
?>

Private members
By designating a member private, you limit its accessibility to the class in which it is declared. The
private member cannot be referred to from classes that inherit the class in which it is declared and
cannot be accessed from outside the class. A class member can be made private by using private
keyword in front of the member.

Protected members
A protected property or method is accessible in the class in which it is declared, as well as in classes
that extend that class. Protected members are not available outside of those two kinds of classes. A
class member can be made protected by using protected keyword in front of the member.

Inheritance
When the properties and the methods of the parent class are accessed by the child class, we call the
concept has inheritance. The child class can inherit the parent method and give own method
implementation, this property is called overridden method. When the same method of the parent
class is inherited we call as inherited method. Now let us see types of inheritance supported in Object
Oriented Programming and corresponding Php inheritance examples.
Types of Inheritance
1. Single Level Inheritance 2. Multilevel Inheritance

PHP (Hypertext PreProcessor) P a g e 166 |


Nandha Arts and Science College PHP – V Unit BCA Department

1. Single Level Inheritance: In Single Level Inheritance the Parent class methods will be extended by the
child class. All the methods can be inherited.

Example – 161
<?php class A {
public function printItem($string) {
echo ' Hi : ' .$string;
}
public function printPHP() {
echo 'I am from Covai' .PHP_EOL;
} }
class B extends A {
public function printItem($string)
{
Output
echo 'Hi: ' . $string .PHP_EOL;
} Hi : Raju

public function printPHP() I am from Covai


{
Hi: saravanan
echo "I am from Salem";
} } I am from Salem
$a = new A();
$b = new B();
$a-> printItem('Raju');
$a-> printPHP();
$b-> printItem('saravanan');
$b-> printPHP();
?>
2. Multilevel Inheritance: In Multilevel Inheritance, the parent

class method will be inherited by child


class and again subclass will inherit the
child class method.
<?php
class A {
public function myage() {
return ' age is 80';
}
}
class B extends A {
public function mysonage() {

PHP (Hypertext PreProcessor) P a g e 167 |


Nandha Arts and Science College PHP – V Unit BCA Department

return ' age is 50';


}
}
class C extends B {
Output
public function mygrandsonage()
{ Class A is 80
return 'age is 20';
Class B is 50
}
public function myHistory() { Class C 20

echo "Class A ".$this->myage();


echo "Class B ".$this-> mysonage();
echo "Class C ".$this->mygrandsonage();
}
}
$obj = new C();
$obj->myHistory();
?>

Abstract Classes:
 An abstract class is a class that contains at least one abstract method. The abstract method is function
declaration without anybody and it has the only name of the method and its parameters.
 There can be any number of methods in the class and we have to declare the class as abstract only
when there is an abstract method.
 In an inheritance hierarchy, subclasses implement specific details, whereas the parent class defines the
framework its subclasses. The parent class also serves a template for common methods that will be
implemented by its subclasses. To make the parent classes more general and abstract, PHP provides
abstract method and abstract class.

Example – 162
<?php
abstract class Cars
{
public abstract function getCompanyName();
public abstract function getPrice();
}
class Baleno extends Cars
{
public function getCompanyName()
{
return "Maruthi Suzuki" . '<br/>';

PHP (Hypertext PreProcessor) P a g e 168 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
public function getPrice()
{
return 720000 . '<br/>';
}
}
class Santro extends Cars {
public function getCompanyName()
{
return "Hyundai" . '<br/>';
}
public function getPrice()
{
return 300000 . '<br/>';
}
}
$car = new Baleno();
Output
$car1 = new Santro();
echo $car->getCompanyName(); Maruthi Suzuki
echo $car->getPrice(); 720000
Hyundai
echo $car1->getCompanyName(); 300000
echo $car1->getPrice();
?>

Notes on Abstract classes:


✓ Objects cannot be created for the abstract classes.
✓ If a class has only one method as abstract, then that class must be an abstract class.
✓ The child class which extends an abstract class must define all the methods of the abstract class.
✓ If the abstract method is defined as protected in the parent class, the function implementation must
be defined as either protected or public, but not private.
✓ Abstract classes that declare all their methods as abstract are not interfaces with different names. One
can implement multiple interfaces, but not extend multiple classes (or abstract classes).
Abstract class Inheritance
It can have constants, members, method stubs It can only have constants and methods stubs.
(methods without a body), methods
Methods and members can have public or Methods of interface should only be public not any
protected visibility other visibility
The concept of multiple inheritances not An interface can extend or a class can implement
supported. multiple other interfaces.
Child class must implement all the abstract
No need of implementing methods from parent
method of parent class when extend keyword is
interface when interface is extending another interface
used.

PHP (Hypertext PreProcessor) P a g e 169 |


Nandha Arts and Science College PHP – V Unit BCA Department

Constructor & Destructors Example Programs


The class "
Example – 163 Constructor " was
<?php initiated.
class Constructor
{
public function __construct() // Constructor
{
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
}
$obj = new Constructor; // Create a new object
?>

Example – 164
<?php The class "
destructors " was
class destructors
destroyed.
{
// Destructor
public function __destruct()
{
echo 'The class "' . __CLASS__ . '" was destroyed!';
}

}
// Create a new object
$obj = new destructors;
?>

HTML Forms:- (Using HTML forms with PHP)


❖ Access single and multiple form values
❖ One of the advantages of PHP has always been the ability to easily manipulate information
submitted by the user through an HTML form.
❖ In fact, PHP version 4.1 adds several new ways to access this information and effectively
removes the one most commonly used in previous versions.
❖ A different ways to use the information submitted on an HTML form, in both older and more
recent versions of PHP.

PHP (Hypertext PreProcessor) P a g e 170 |


Nandha Arts and Science College PHP – V Unit BCA Department

❖ It starts out by looking at individual values and builds to a page that can generically access
any available form values.
❖ During the course of the article, you'll look at how different types of HTML form elements
provide information that PHP can access.
❖ HTML Forms are required, when you want to collect some data from the site visitor. For example, during
user registration you would like to collect information such as name, email address, credit card, etc.
❖ A form will take input from the site visitor and then will post it to a back-end application such
as CGI, ASP Script or PHP script etc. The back-end application will perform required processing
on the passed data based on defined business logic inside the application.
❖ There are various form elements available like text fields, textarea fields, drop-down menus,
radio buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following syntax:
<form action="Script URL" method="GET|POST">
form elements like input, textarea etc.
</form>

Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes:
Attribute Description

action Backend script ready to process your passed data.

method Method to be used to upload data. The most frequently used are GET & POST methods.

target Specify the target window or frame where the result of the script will be displayed.
It takes values like _blank, _self, _parent etc.

enctype You can use the enctype attribute to specify how the browser encodes the data before
it sends it to the server.

Form Controls
There are different types of form controls that you can use to collect data using HTML form:
• Text Input Controls • Select Box Controls • Clickable Buttons
• Checkboxes Controls • File Select boxes • Submit and Reset Button
• Radio Box Controls • Hidden Controls

PHP (Hypertext PreProcessor) P a g e 171 |


Nandha Arts and Science College PHP – V Unit BCA Department

Text Input Controls There are three types of text input used on forms:

Single-line text input controls - This control is used for items that require only one line of user
input, such as search boxes or names. They are created using
HTML <input> tag.
Password input controls - This is also a single-line text input but it masks the character as
soon as a user enters it. They are also created using HTMl <input>
tag.
Multi-line text input controls - This is used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are
created using HTML <textarea> tag.

Single-line text input controls


This control is used for items that require only one line of user input, such as search boxes or names.
They are created using HTML <input> tag.

Example – 165 Here is a basic example of a single-line text input used to take first name and last name:
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type="text" name="first_name" />
<br>
Last name: <input type="text" name="last_name" />
</form>
</body>
</html>
This will produce the following result:

First name: Last name:

Attributes
Following is the list of attributes for <input> tag for creating text field.
Attribute Description
type Indicates the type of input control and for text input control it will be set to text.

PHP (Hypertext PreProcessor) P a g e 172 |


Nandha Arts and Science College PHP – V Unit BCA Department

name Used to give a name to the control which is sent to the server to be recognized and get the value.
value This can be used to provide an initial value inside the control.
size Allows to specify the width of the text-input control in terms of characters.
maxlength Allows to specify the maximum number of characters a user can enter into the text box.
Password Input controls
This is also a single-line text input but it masks the character as soon as a user enters it. They are also
created using HTML <input> tag but type attribute is set to password.

Example – 166 Here is a basic example of a single-line password input used to take user password:
<html>
<head>
<title>Password Input Control</title>
</head>
<body>
<form >
User ID : <input type="text" name="user_id" />
<br>
Password: <input type="password" name="password" />
</form>
</body>
</html>
This will produce the following result:
User ID : Password:

Attributes
Following is the list of attributes for <input> tag for creating password field.
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized and
get the value.
value This can be used to provide an initial value inside the control.

size Allows to specify the width of the text-input control in terms of characters.

maxlength Allows to specify the maximum number of characters a user can enter into the text box.

Multiple-Line Text Input Controls


This is used when the user is required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.

PHP (Hypertext PreProcessor) P a g e 173 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 167 Here is a basic example of a multi-line text input used to take item description:
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form>
Description: <br />
<textarea rows="5" cols="50" name="description"> Enter description here...
</textarea>
</form>
</body>
</html>

Attributes
Following is the list of attributes for <textarea> tag.
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized and get the value.
rows Indicates the number of rows of text area box.

cols Indicates the number of columns of text area box

Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox.

Example – 168 Here is an example HTML code for a form with two checkboxes:

<html>
<head>
<title>Checkbox Control</title></head>
<body>
<form>
<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
</form>
</body> </html>
This will produce the following result:
Maths Physics

PHP (Hypertext PreProcessor) P a g e 174 |


Nandha Arts and Science College PHP – V Unit BCA Department

Attributes
Following is the list of attributes for <checkbox> tag.
Attribute Description
type Indicates the type of input control and for checkbox input control it will be set to checkbox.
name Used to give a name to the control which is sent to the server to be recognized and get
the value.

value The value that will be used if the checkbox is selected.

checked Set to checked if you want to select it by default.

Radio Button Control


Radio buttons are used when out of many options, just one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set to radio.

Example – 169 Here is example HTML code for a form with two radio buttons:
<html>
<head>
<title>Radio Box Control</title>
</head>
<body>
<form>
<input type="radio" name="subject" value="maths"> Maths
<input type="radio" name="subject" value="physics"> Physics
</form>
</body>
</html>
This will produce the following result:

Maths Physics

Attributes
Following is the list of attributes for radio button.
Attribute Description
type Indicates the type of input control and for checkbox input control it will be set to radio.
name Used to give a name to the control which is sent to the server to be recognized and get the value.
value The value that will be used if the radio box is selected.
checked Set to checked if you want to select it by default.
Select Box Control
A select box, also called drop down box which provides option to list down various options in the form
of drop down list, from where a user can select one or more options.

PHP (Hypertext PreProcessor) P a g e 175 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 170 Here is example HTML code for a form with one drop down box
<html>
<head>
<title>Select Box Control</title> </head>
<body>
<form>
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select> </form>
</body>
</html>
This will produce the following result:
Maths

Attributes
Following is the list of important attributes of <select> tag:
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized
and get the value.
size This can be used to present a scrolling list box.

multiple If set to "multiple" then allows a user to select multiple items from the menu.
Following is the list of important attributes of <option> tag:
Attribute Description
value The value that will be used if an option in the select box box is selected.
selected Specifies that this option should be the initially selected value when the page loads.
label An alternative way of labelling options

Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable button using
<input> tag by setting its type attribute to button. The type attribute can take the following values:
Type Description
submit This creates a button that automatically submits a form.

reset This creates a button that automatically resets form controls to their initial values.
button This creates a button that is used to trigger a client-side script when the user clicks that button.
image This creates a clickable button but we can use an image as background of the button.

PHP (Hypertext PreProcessor) P a g e 176 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 171
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
<input type="image" name="imagebutton" src="/html/images/logo.png" />
</form>
</body>
</html>

This will produce the following result: Submit Reset

HTTP authentication with PHP:


It is possible to use the header() function to send an "Authentication Required" message to the client
browser causing it to pop up a Username/Password input window.
HTTP Basic authentication is way to authenticate where user agent password the user information to
server and server authenticates the given user detail and provide further access. While information get
transmitted to server they are base64 encoded. Its server responsibility to validate the detail. If you are
using Apache as web server you can implement basic auth using .htaccess and htpasswd with password
file. But if you want you can implement http basic authentication with PHP also. In this tutorial we will
explore on http basic authentication php. First we will explore on how exactly http authentication
works. Once you will have idea of how it works you can easily write PHP code. So later in the later part
of tutorial we will cover our real topic i.e. HTTP basic authentication php.
What is HTTP basic Authentication and how it works
HTTP basic authentication is mechanism to validate user. In HTTP basic authentication browser takes
username and password from user in input box like above image and send back to server. Server then
validate the detail and found it correct then grant the require access of pages to user. If server found
user un-authenticated then again ask browser to get user detail and then again browser ask user to
input user detail. If user completely deny to enter user detail then server send 401 HTTP code.

PHP (Hypertext PreProcessor) P a g e 177 |


Nandha Arts and Science College PHP – V Unit BCA Department

Now the question is, how these complex communication happens between server and browser?
While in complete HTTP basic auth process server and browser communicate via HTTP header. Below
are the step by step process with HTTP header on how server and browser communicate in HTTP basic
authentication process:
1. User request for the HTTP basic author protected page via web browser.
2. Server send the following header to browser so that browser can ask user to enter the
password:

Basic HTTP Authentication Example:


Example – 172
<?php

if (!isset($_SERVER['PHP_AUTH_USER']))

header('WWW-Authenticate: Basic realm="My Realm"');

header('HTTP/1.0 401 Unauthorized');

echo 'Text to send if user hits Cancel button';

exit;

else

echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";

echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your

password.</p>";

?>

PHP (Hypertext PreProcessor) P a g e 178 |


Nandha Arts and Science College PHP – V Unit BCA Department

Design Window Output

Hello Raja.

You entered 12345 as


your password.

Digest HTTP Authentication example:


The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and
is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the
header() function to send an "Authentication Required" message to the client browser causing it to
pop up a Username/Password input window. Once the user has filled in a username and a password,
the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER,
PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type
respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays.
Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported.

Example – 173
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST']))
{
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response

PHP (Hypertext PreProcessor) P a g e 179 |


Nandha Arts and Science College PHP – V Unit BCA Department

$A1 = md5($data['username'] . ':' . $realm . ':' .


$users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.
$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1,
'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([>\2]+?)\2|
([>\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m)
{
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>

PHP Cookies:
A cookie is often used to identify a user.

What is a Cookie?
• Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
• There are three steps involved in identifying returning users:
• Server script sends a set of cookies to the browser. For Example, name, age, or identification
number etc.

PHP (Hypertext PreProcessor) P a g e 180 |


Nandha Arts and Science College PHP – V Unit BCA Department

• Browser stores this information on local machine for future use.


• Next time, when the browser sends any request to the web server, it sends those cookies
information to the server and server uses that information to identify the user.
• A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer.
• Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A PHP script that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX)
PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to "forget"
the cookie after the given time and date.

Setting (or) Creating Cookies with PHP


PHP provided setcookie() function to set a cookie. This function requires up to six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value - This sets the value of the named variable and is the content that you actually want to store.

Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time
cookie will become inaccessible. If this parameter is not set, then cookie will
automatically expire when the Web Browser is closed.

Path - This specifies the directories for which the cookie is valid. A single forward slash

PHP (Hypertext PreProcessor) P a g e 181 |


Nandha Arts and Science College PHP – V Unit BCA Department

character permits the cookie to be valid for all directories.


Domain - This can be used to specify the domain name in very large domains and must contain at least two
periods to be valid. All cookies are only valid for the host and domain which created them.

Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using
HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
The following example will create two cookies name and age. These cookies will expire after an hour.

Example – 174
<?php
setcookie("name", "John", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html> <head> <title>Setting Cookies with PHP</title> </head>
<body> <?php echo "Set Cookies"?> </body> </html>

Accessing Cookies with PHP


PHP provides many ways to access cookies. The simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. The following example will access all the cookies set in above example.

Example – 175
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
You can use isset() function to check if a cookie is set or not.

PHP (Hypertext PreProcessor) P a g e 182 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 176
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?> </body> </html>

Deleting Cookie with PHP


Officially, to delete a cookie you should call setcookie() with the name argument only but this does not
always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired:

Example – 177
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
// set the expiration date to one hour ago setcookie("user", "", time()-3600);
?>
<html> <head>
<title>Deleting Cookies with PHP</title> </head>
<body> <?php echo "Deleted Cookies" ?>
</body> </html>

Handling File Uploads:


 A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
 Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded
is stated as upload_max_filesize. These parameters are set into PHP configuration
filephp.ini

PHP (Hypertext PreProcessor) P a g e 183 |


Nandha Arts and Science College PHP – V Unit BCA Department

The process of uploading a file follows these steps:


 The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
 The user clicks the browse button and selects a file to upload from the local PC.
 The full path to the selected file appears in the text field, then the user clicks the submit
button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action attribute checks
that the file has arrived and then copies the file into an intended directory.
 The PHP script confirms the success to the user.

Example – 178
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else
{
print_r($errors);
}

PHP (Hypertext PreProcessor) P a g e 184 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>

File Handling:
Opening a file:
• The fopen( ) function is used to open the file in PHP.
• The first parameter of this function contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened.

Example – 179
<html>
Mode Description
<head>
r Read only, start at the beginning of the file.
<body>
r++ Read, write at the beginning of the file.
<?php
w Write only, open the content of the file or
$file = fopen ("Welcome.txt", 'r'); creates a new file.
?> w++ Read Write, only open the content of the file
or create a new file.
</head> a Append.

</body> a++ Read append.

</html>

Closing a file: The fclose( ) is used to close an open file.

Example – 180
<?php
$file = fopen(" test.txt", "r");
fclose($file);
?>

Check end of file: The end of the file by using feof( ) function checks if the end of the file has been reached.

PHP (Hypertext PreProcessor) P a g e 185 |


Nandha Arts and Science College PHP – V Unit BCA Department

Definition and Usage


 The feof() function checks if the "end-of-file" (EOF) has been reached.
 This function returns TRUE if an error occurs, or if EOF has been reached. Otherwise it returns
FALSE.
 The feof() function is useful for looping through data of unknown length.

Example – 181
<?php
$file = fopen("test.txt", "r");
//Output a line of the file until the end is reached
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file); ?>
Reading a file line by line: The fgets( ) function is used to read a single line from a file.

Example – 182
The output of the code above will be:
<html> Hello, this is a test file.
<body> There are three lines here.
<?php This is the last line.
$file = fopen("Welcome.txt", "r");
while( !eof($file))
{
echo fgets($file);
}
fclose($file);
?>
</body> </html>
Reading a file character by character: The function fgetc( ) used to read a file character by character.

Example – 183
<html> <body> <?php
$file = fopen("Welcome.txt", "r");
While( !eof($file))
{
echofgetc($file);

PHP (Hypertext PreProcessor) P a g e 186 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
fclose($file);
?>
</body> </html>

Reading a file into an array with file:


The file function is used to read a file into an array all at once. each line becomes an element in the array.
Filename (filename. Extension)

Example – 184 We can display line numbers of a file <html>


<head>
<title> Reading a file in an array</title>
</head>
<body>
<h1> Reading a file into an array</h1>
<?php
$data = file(" file.txt");
foreach($data as $number -> $line)
{
echo "line number", $line ;"<br>
}
?> </body> </html>
The entire a file, file.txt was read into an array and displayed. You can also open a web page and read
them into arrays using the file function.

Example – 185
<html> <head>
<title> Reading a page into an array</title>
</head>
<body>
<h1> Reading a page into an array</h1>
<?php
$data = file(" http:// www.php.net");
foreach($data as $number -> $line)
{
echo "line number", $line ;"<br>
}
?> </body> </html>

PHP (Hypertext PreProcessor) P a g e 187 |


Nandha Arts and Science College PHP – V Unit BCA Department

Getting file size with file size of function:


We can get file size returned by file size function, returned as integer. Filesize(filename. extension)
We can pass the file name including path to file size and false if the file does not exist.

Example – 186
<html> <head>
<title> Getting file size</title>
</head>
<body>
<h1> Getting file size</h1>
<?php
echo "The file size.txt is" file size("file.txt") " bytes long";
?> </body> </html>

PHP file Uploads:


 With PHP it's possible to upload files to the server.
 The type attribute of the form tag specifies which content type to use when submitting a form.
 "Multipart/form-data" if used when a form requires binary data. Like the contains of the file
to be upload.
 The type = "file" attribute of the input tag specifies the input should be process as a title.
Create an Upload File:
To allow a user's to upload the files from a form can be very useful.

Example – 187
<html>
<head>
<title> Creating an upload file </title> </head>
<body>
<form action = "upload-file.php" Method = "post" enctype = "Multipart / form.data ">
<label for = "file"> filename : </label>
<input type = "file" name = "file" ie\ = "file" ></input><br>
<input type = "submit" name = "submit" value = "submit"> </input>
</form>
</body>
</html>

PHP (Hypertext PreProcessor) P a g e 188 |


Nandha Arts and Science College PHP – V Unit BCA Department

Using Remote Files:


 As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most
of the functions that take a filename as a parameter. In addition, URLs can be used with the
include(), include_once(), require() and require_once() statements. In PHP 4.0.3 and older,
in order to use URL wrappers, you were required to configure PHP using the configure option
–enable-url-fopen-wrapper.
Transfer Files Server to Server
 It debugged code and found
Using Simple PHP
that allow_url_fopen function is
used to fetch tweets from
website(web page) and
allow_url_fopen function is off in
live web server. Mostly this PHP parameter allow_url_fopen has been disabled by default on
live server and that means that once allow_url_fopen is set as off, your application cannot
retrieve remote files at all.
 If allow_url_fopen is off, can’t retrieve remote files or remote URL in PHP. The open() function
and the include and require directives can retrieve remote files if allow_url_fopen is on and
we can set this by php.ini.
 To open remote files with fopen() is implemented by a PHP feature called the URL fopen
wrapper. It’s enabled by default but if it’s disabled by setting allow_url_fopen to off. If you
can’t open/access remote
files with fopen(), check your
server configuration.

To read a remote file from php you have at least four options :
1. Use fopen() 2. Use file_get_contents()
3. CURL 4. Make your own function using php's socket functions.
First i need to warn you about something. You can only use fopen() and file_get_contents() when
fopen wrappers is enabled. This parameter is specified in the php.ini file and cannot be changed at
run time using ini_set(), To know whether you can use these two or not you can use the following
code to check the value of fopen wrapper setting.

PHP (Hypertext PreProcessor) P a g e 189 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example
if (ini_get('allow_url_fopen') == '1')
{
// use fopen() or file_get_contents()
} else {
// use curl or your custom function
}

1 . Using fopen()
If you use fopen() to read a remote file the process is as simple as reading from a local file. The only
difference is that you will specify the URL instead of the file name. Take a look at the example below :

Example – 188
if ($fp = fopen('http://www.google.com/', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
} else {
}
Now, the code above use fread() function in the while loop to read up to 1024 bytes of data in a
single loop. That code can also be written like this :

Example – 189 // make sure the remote file is successfully opened before doing anything else

if ($fp = fopen('http://www.google.com/', 'r'))


{
$content = '';
while ($line = fgets($fp, 1024))
{
$content .= $line;
}
} else {
// an error occured when trying to open the specified url
}
instead of fread() we use fgets() which reads one line of data up to 1024 bytes.

PHP (Hypertext PreProcessor) P a g e 190 |


Nandha Arts and Science College PHP – V Unit BCA Department

2. Using file_get_contents()
This is my favorite way of reading a remote file because it is very simple. Just call this function and
specify a url as the parameter. But make sure you remember to check the return value first to
determine if it return an error before processing the result
$content = file_get_contents('http://www.google.com/');
if ($content !== false)
{
// do something with the content
} else
URL stands for Uniform Resource Locator, and is
{
used to specify addresses on the World Wide
// an error happened Web. A URL is the fundamental network
identification for any resource connected to the
}
web (e.g., hypertext pages, images, and sound
3. CURL(Client Uniform Resource Locator) files). The protocol specifies how information
from the link is transferred.
The CURL library ('libcurl' which is the package name
on the server) is often used in PHP to access data from
RSS, in its current form, stands for Really Simple
outside web pages. Syndication and is a family of web formats to
Common uses include reading rss feeds or accessing publish frequently updated content. The RSS
Feed (as it is commonly known) can then be read
third-party API systems. libcurl currently supports the by the users feed reading software or by another
website which wishes to 'syndicate' the content
http, https, ftp, gopher, telnet, dict, file, and ldap of that feed.
protocols. Unlike the two methods above using CURL
cannot be said as straight forward. Although this library
is very useful to connect and communicate with many Gzip is a method of compressing files (making
them smaller) for faster network transfers. It is
different protocols it requires more effort to learn. And also a file format. Compression allows your web
server to provide smaller file sizes which load
another problem is that not all web host have this
faster for your website users. Enabling gzip
library in their php installation. compression is a standard practice

In some cases using CURL is faster than using


file_get_contents() or fopen(). This is because CURL handles compression protocols by default. Many
sites, big and small, use gzip compression to compress their web pages in order to save bandwidth.
This site, for example, also use gzip compression which cut the bandwidth used into half. So if you're
the type who just can't wait CURL will fit you most.

4. Custom functions
In the worst case your server will have fopen wrappers disabled and don't have CURL library installed.
In this sad situation you just have to make your own way.
Our function shall be named getRemoteFile() which takes only one parameter, the url for the remote

PHP (Hypertext PreProcessor) P a g e 191 |


Nandha Arts and Science College PHP – V Unit BCA Department

file. The skeleton for this function is shown below


function getRemoteFile($url)
{
// 1. get the host name and url path
// 2. connect to the remote server
// 3. send the necessary headers to get the file
// 4. retrieve the response from the remote server
// 5. strip the headers
// 6. return the file content
}

Example – 190 Getting the title of a remote page


<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line *
/
if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
You can also write to files on an FTP server (provided that you have connected as a user with the correct
access rights). You can only create new files using this method; if you try to overwrite a file that already
exists, the fopen() call will fail.

PHP (Hypertext PreProcessor) P a g e 192 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 191 Storing data on remote server

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To
do distributed logging like that, you should take a look at syslog().

Connection Handling:
Definition and Usage
The connection_status() function returns the current connection status.
Internally in PHP a connection status is maintained. There are 4 possible states:
0 - CONNECTION_NORMAL - connection is running normally
1 - CONNECTION_ABORTED - connection is aborted by user or network error
2 - CONNECTION_TIMEOUT - connection timed out
3 - CONNECTION_ABORTED & CONNECTION_TIMEOUT
Syntax connection_status()
✓ When a PHP script is running normally, the NORMAL state is active. If the remote client
disconnects, the ABORTED state flag is turned on.
✓ A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-
imposed time limit (see set time limit()) is hit, the TIMEOUT state flag is turned on.
✓ You can decide whether or not you want a client disconnect to cause your script to be aborted.
Sometimes it is handy to always have your scripts run to completion even if there is no remote
browser receiving the output.
✓ The default behaviour is however for your script to be aborted when the remote client disconnects.
✓ This behaviour can be set via the ignore_user_abortphp.ini directive as well as through the
corresponding php_valueignore_user_abort Apache httpd.conf directive or with the ignore
user abort() function.
✓ If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The

PHP (Hypertext PreProcessor) P a g e 193 |


Nandha Arts and Science College PHP – V Unit BCA Department

one exception is if you have registered a shutdown function using register shutdown
function().
✓ With a shutdown function, when the remote user hits his STOP button, the next time your
script tries to output something PHP will detect that the connection has been aborted and the
shutdown function is called.
✓ This shutdown function will also get called at the end of your script terminating normally, so
to do something different in case of a client disconnect you can use the connection abortedQ
function. This function will return TRUE if the connection was aborted.
✓ When the timer expires the script will be aborted and as with the above client disconnect case,
if a shutdown function has been registered it will be called.
✓ Within this shutdown function you can check to see if a timeout caused the shutdown function
to be called by calling the connection status() function.
✓ This function will return 2 if a timeout caused the shutdown function to be called.
✓ One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time.
✓ This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may
have broken the connection, but the script will keep running.
✓ If it then hits the time limit it will be aborted and your shutdown function, if any, will be called.
At this point you will find that connection status() returns 3.
Example – 192
<html>
<body>
<?php
switch (connection_status())
{
case CONNECTION_NORMAL:
$txt = 'Connection is in a normal state';
break;
case CONNECTION_ABORTED:
$txt = 'Connection aborted';
break;
case CONNECTION_TIMEOUT:
$txt = 'Connection timed out';
break;
case (CONNECTION_ABORTED & CONNECTION_TIMEOUT):
$txt = 'Connection aborted and timed out';

PHP (Hypertext PreProcessor) P a g e 194 |


Nandha Arts and Science College PHP – V Unit BCA Department

break;
default:
$txt = 'Unknown';
Connection is in a
break; normal state
}
echo $txt;
?> </body> </html>

MYSQL
Beginner
 MySQL is an open source relational database management system (RDBMS) based on
Structured Query Language (SQL).
 MySQL runs on virtually all platforms, including Linux, UNIX, and Windows. Although it
can be used in a wide range of applications, MySQL is most often associated with web-
based applications and online publishing and is an important component of an open
source enterprise stack called LAMP.
 LAMP is a Web development platform that uses Linux as the operating system, Apache
as the Web server, MySQL as the relational database management system and PHP as
the object-oriented scripting language.

What is my SQL database?


 MySQL is a freely available open source RDBMS that uses SQL.
 SQL is the most popular language for adding, accessing and managing content in a database.
It is most noted for its quick processing, proven reliability, ease & flexibility of use.
 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 compiles on a number of platforms
 MySQL is free to download and use

PHP (Hypertext PreProcessor) P a g e 195 |


Nandha Arts and Science College PHP – V Unit BCA Department

 MySQL is a fast, easy to use relational database. It is currently the most popular open-
source database. It is very commonly used in conjunction with PHP scripts to create
powerful and dynamic server-side applications.
 MySQL is used for many small and big businesses. It is developed, marketed and
supported by MySQL AB, a Swedish company. It is written in C and C++.
 MySQL is becoming so popular because of these following reasons:
 MySQL is an open-source database so you don't have to pay a single penny to use it.
 MySQL is a very powerful program so it can handle a large set of functionality of the
most expensive and powerful database packages.
 MySQL is customizable because it is an open source database and the open-source GPL
license facilitates programmers to modify the SQL software according to their own
specific environment.
 MySQL is quicker than other databases so it can work well even with the large data set.
 MySQL supports many OS with many languages like PHP, PERL, C, C++, JAVA, etc.
 MySQL uses a standard form of the well-known SQL data language.
 MySQL is very friendly with PHP, the most popular language for web development.
 MySQL supports large databases, up to 50 million rows or more in a table.
 The default file size limit for a table is 4GB, but you can increase this to a theoretical
limit of 8 million TB.
 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.

What is the meaning of open source database?


 LAMP stands for Linux, Apache Web server, MySQL database and the PHP/Python/Perl
development languages. It is a collective of open source software that can be used to
deploy applications with minimal cost, which is the interesting part to most of its
adopter.

History
 MySQL was created by a Swedish company, MySQL AB, founded by David Axmark, Allan
Larsson and Michael "Monty" Widenius. Original development of MySQL by Widenius
and Axmark began in 1994.

PHP (Hypertext PreProcessor) P a g e 196 |


Nandha Arts and Science College PHP – V Unit BCA Department

 MySQL AB was acquired by Sun Microsystems in 2008 and then by Oracle when it
bought Sun in 2010. Developers can still use MySQL under the GNU General Public
License (GPL), but enterprises must obtain a commercial license from Oracle.

What is a server in a database?


 A database server is a computer program that provides database services to other
computer programs or to computers, as defined by the client–server model. The term
may also refer to a computer dedicated to running such a program.

What is a database server and application server?


 This server will have installed web servers such as IIS, apache, etc. Application Server -
Server on which you’re created applications which are utilizing your database, web
service, etc. This application server will host business layer (wrapped with web
services), scheduled jobs, windows services, etc. Oct 24, 2012.

SQL vs. MySQL


 SQL stands for Structured Query Language. It’s a standard language for accessing and
manipulating databases. MySQL is a database management system, like SQL Server,
Oracle, Informix, Postgres, etc. MySQL is a RDMS.
 When considering a utility for data management the two most popular choices are
MySQL and SQL Server. Both are efficient at keeping your data organized and readily
available through a user interface.
 SQL is a language. Specifically, the “Structured Query Language” Now it would be better
if we start differentiating the topic as difference between SQL server and MySQL and
take them point by point.

MySQL Data Types In MySQL there are three main data types: text, number & Date/Time types.
Text types:
Data type Description
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is
CHAR(size)
specified in parenthesis. Can store up to 255 characters
Holds a variable length string (can contain letters, numbers, and special characters). The maximum
VARCHAR(size)
size is specified in parenthesis. Can store up to 255 characters.
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters

PHP (Hypertext PreProcessor) P a g e 197 |


Nandha Arts and Science College PHP – V Unit BCA Department

BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is
ENUM(x,y,z,etc.)
inserted that is not in the list, a blank value will be inserted.
SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

Number types:
Data type Description

TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified
in parenthesis

SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be
specified in parenthesis

MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits
may be specified in parenthesis

INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum


number of digits may be specified in parenthesis

BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615


UNSIGNED*. The maximum number of digits may be specified in parenthesis

FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be
specified in the size parameter.

DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be
specified in the size parameter.

DECIMAL(size,d) A DOUBLE stored as a string, allowing for a fixed decimal point. The maximum number of
digits may be specified in the size parameter.
Date types:
Data type Description

A date. Format: YYYY-MM-DD


DATE()
Note: The supported range is from '1000-01-01' to '9999-12-31'

*A date and time combination. Format: YYYY-MM-DD HH:MI:SS


DATETIME()
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix
TIMESTAMP() epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC

A time. Format: HH:MI:SS


TIME()
Note: The supported range is from '-838:59:59' to '838:59:59'
A year in two-digit or four-digit format.
YEAR() Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit
format: 70 to 69, representing years from 1970 to 2069

PHP (Hypertext PreProcessor) P a g e 198 |


Nandha Arts and Science College PHP – V Unit BCA Department

Create Database
Syntax: CREATE DATABASE database_name;
Example: CREATE DATABASE Student;
SELECT Database
SELECT Database is used in MySQL to select a particular database to work with. This query is
used when multiple databases are available with MySQL Server.
You can use SQL command USE to select a particular database.
Syntax: USE database_name;
Example: USE customers;
Drop Database
You can drop/delete/remove a MySQL database easily with the MySQL command. You should be
careful while deleting any database because you will lose your all the data available in your database.
Syntax: DROP DATABASE database_name;
Example: DROP DATABASE employees;
CREATE TABLE
The MySQL CREATE TABLE command is used to create a new table into the database. A table creation
command requires three things:
1. Name of the table
2. Names of fields
3. Definitions for each field
Syntax: CREATE TABLE table_name (column_name column_type...);
Example:
CREATE TABLE cus_tbl(
cus_id INT NOT NULL AUTO_INCREMENT,
cus_firstname VARCHAR(100) NOT NULL,
cus_surname VARCHAR(100) NOT NULL,
PRIMARY KEY ( cus_id )
);
See the created table: The table already created: SHOW tables;
See the table structure: The table already created: DESCRIBE cus_tbl;
ADD a column in the table
Syntax: ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];

PHP (Hypertext PreProcessor) P a g e 199 |


Nandha Arts and Science College PHP – V Unit BCA Department

Database Connections:
✓ MySQLi extension (the "i" stands for improved)
✓ PDO (PHP Data Objects)
mysql_connect — Open a connection to a MySQL Server
Description Resource mysql_connect ( [ string $server = ini_get("mysql.default_host")
[, string $username = ini_get("mysql.default_user")
[, string $password = ini_get("mysql.default_password")
[, bool $new_link = false
[, int $client_flags = 0 ]]]]] )
Opens or reuses a connection to a MySQL server.

Example – 193 (MySQLi Object-Oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Example – 194 (MySQL PDO)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",$username,$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";

PHP (Hypertext PreProcessor) P a g e 200 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Close the Connection


Example (MySQLi Procedural) -> mysqli_close($conn);
Example (PDO) -> $conn = null;

Parameters
server
The MySQL server. It can also include a port number.
e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.
If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'.
In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.
username
The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter
is ignored and the name of the user that owns the server process is used.
password
The password. Default value is defined by mysql.default_password. In SQL safe mode, this
parameter is ignored and empty password is used.
new_link
The new_link parameter modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same parameters. In SQL safe mode,
this parameter is ignored.
client_flags
The client_flags parameter can be a combination of the following constants: 128 (enable LOAD
DATA LOCAL handling),
MYSQL_CLIENT_SSL,
MYSQL_CLIENT_COMPRESS,
MYSQL_CLIENT_IGNORE_SPACE or
MYSQL_CLIENT_INTERACTIVE.

PHP (Hypertext PreProcessor) P a g e 201 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 195 (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Note: The following PDO example create a database named "myDBPDO":

Example – 196 (MySQL PDO)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);

PHP (Hypertext PreProcessor) P a g e 202 |


Nandha Arts and Science College PHP – V Unit BCA Department

echo "Database created successfully<br>";


}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Create a MySQL Table Using MySQLi and PDO


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":
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
)
Notes on the table above:
The data type specifies what type of data the column can hold. For a complete reference of all the
available data types, go to our Data Types reference.
After the data type, you can specify other optional attributes for each column:
• NOT NULL - Each row must contain a value for that column, null values are not allowed
• DEFAULT value - Set a default value that is added when no other value is passed
• UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a
new record is added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY
KEY setting is often an ID number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must be
unique for each record in the table.

PHP (Hypertext PreProcessor) P a g e 203 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 197 (MySQLi Procedural)


<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_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 (mysqli_query($conn, $sql)) {

echo "Table MyGuests created successfully";

} else {

echo "Error creating table: " . mysqli_error($conn);

mysqli_close($conn);

?>

PHP (Hypertext PreProcessor) P a g e 204 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 198 (PDO)


<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// set the PDO error mode to exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 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

)";

// use exec() because no results are returned

$conn->exec($sql);

echo "Table MyGuests created successfully";

catch(PDOException $e)

echo $sql . "<br>" . $e->getMessage();

$conn = null;

?>

PHP (Hypertext PreProcessor) P a g e 205 |


Nandha Arts and Science College PHP – V Unit BCA Department

Insert Data into MySQL Using MySQLi and PDO


After a database and a table have been created, we can start adding data in them.

• The SQL query must be quoted in PHP

• String values inside the SQL query must be quoted

• Numeric values must not be quoted

• The word NULL must not be quoted

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,...)

Example – 199 (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP (Hypertext PreProcessor) P a g e 206 |


Nandha Arts and Science College PHP – V Unit BCA Department

Example – 200 (PDO)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Insert Multiple Records


Example – 201 (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

PHP (Hypertext PreProcessor) P a g e 207 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Example - 202 (PDO)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction(); // our SQL statements
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')");
// commit the transaction
$conn->commit();
echo "New records created successfully";

PHP (Hypertext PreProcessor) P a g e 208 |


Nandha Arts and Science College PHP – V Unit BCA Department

}
catch(PDOException $e)
{ // roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Example - 203 Students Marks details


// Form Design form
<?php
include 'database.php';
?>
<html>
<head>
<!-- <style type="text/css">
#in_class input {
padding: 5px;
margin-top: 10px;
border-radius: 3px;
}
button{
background: green;
color: white;
padding: 5px;
}
</style> -->
</head>
<body>
<br>
<div class="row">
<div class="col-md-4">
<form action="add.php" method="post">
<!-- <div id="in_class" class="in_class"> -->

PHP (Hypertext PreProcessor) P a g e 209 |


Nandha Arts and Science College PHP – V Unit BCA Department

<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Name"
/><br>
<input type="number" name="m1" id="m1" class="form-control"
placeholder="Mark1" /><br>
<input type="number" name="m2" id="m2" placeholder="Mark2" class="form-
control" /><br>
<input type="number" name="m3" id="m3" placeholder="Mark3" class="form-
control" onchange="cal();" /><br>

<input type="number" name="total" id="total" class="form-control"


placeholder="total" /><br>
<input type="number" name="avg" id="avg" class="form-control"
placeholder="avg" /><br>
<input type="text" name="result" id="result" class="form-control"
placeholder="Result" /><br>
</div>
<button class="btn btn-primary" type="submit"
name="submit">Submit</button>
<button class="btn btn-success" type="reset">Reset</button>
</form>
</div>
<script type="text/javascript">
function cal() {
var m1 = document.getElementById('m1').value;
var m2 = document.getElementById('m2').value;
var m3 = document.getElementById('m3').value;
var total = parseInt(m1)+parseInt(m2)+parseInt(m3);
var avg = parseInt(total)/3;
if( parseInt(m1) < 35 || parseInt(m2) < 35 || parseInt(m3) < 35){
$("#result").val("Fail");
}
else{
$("#result").val("Pass");
}

PHP (Hypertext PreProcessor) P a g e 210 |


Nandha Arts and Science College PHP – V Unit BCA Department

$("#total").val(total);
$("#avg").val(avg);
}
</script>
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Mark3</th>
<th>Total</th>
<th>Average</th>
<th>Result</th>
</tr>
<?php
$query = "SELECT * FROM m1";
$res = mysqli_query($db,$query);
$row = mysqli_num_rows($res);
$i = 1;
if($row > 0) {
while($list = mysqli_fetch_assoc($res)){
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $list['name']; ?></td>
<td><?php echo $list['m1']; ?></td>
<td><?php echo $list['m2']; ?></td>
<td><?php echo $list['m3']; ?></td>
<td><?php echo $list['total']; ?></td>
<td><?php echo $list['avg']; ?></td>
<td><?php echo $list['result']; } } ?></td>
</tr>

PHP (Hypertext PreProcessor) P a g e 211 |


Nandha Arts and Science College PHP – V Unit BCA Department

</table>
</div>
</body>
<html>
//add.php
<html>
<body>
<?php
include 'database.php';
$name= $_POST['name'];
$m1 = $_POST['m1'];
$m2 = $_POST['m2'];
$m3 = $_POST['m3'];
$total = $_POST['total'];
$avg = $_POST['avg'];
$result = $_POST['result'];
$query = "INSERT INTO m1(name,m1,m2,m3,total,avg,result)
VALUES('$name','$m1','$m2','$m3','$total','$avg','$result')";
$res = mysqli_query($db,$query);

if(isset($res)){
echo "Data Saved";
header('location:add_mark.php');
}
?>
</body>
</html>
//database Connection
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "mark1";

$db = mysqli_connect($host,$user,$password,$database);

if(!isset($db)){
echo "Database Not Connect";
}

PHP (Hypertext PreProcessor) P a g e 212 |


Nandha Arts and Science College PHP – V Unit BCA Department

?>
// add_marks

<?php
include 'database.php';
?>
<html>
<head>
<style type="text/css">
#in_class input{
padding: 5px;
margin-top: 10px;
border-radius: 3px;
}
button{
background: green;
color: white;
padding: 5px;
}
</style>
</head>
<body>
<form action="add.php" method="post">
<div id="in_class" class="in_class">
<input type="text" name="name" placeholder="Name" /><br>
<input type="number" name="m1" id="m1" placeholder="Mark1" /><br>
<input type="number" name="m2" id="m2" placeholder="Mark2" /><br>
<input type="number" name="m3" id="m3" placeholder="Mark3"
onchange="cal();" /><br>

<input type="number" name="total" id="total" placeholder="total" /><br>


<input type="number" name="avg" id="avg" placeholder="avg" /><br>
<input type="text" name="result" id="result" placeholder="Result"
/><br>
</div>

<button type="submit" name="submit">Submit</button>


<button type="reset">Reset</button>
</form>

<script type="text/javascript">
function cal() {
var m1 = document.getElementById('m1').value;
var m2 = document.getElementById('m2').value;
var m3 = document.getElementById('m3').value;

var total = parseInt(m1)+parseInt(m2)+parseInt(m3);


var avg = parseInt(total)/3;
if( parseInt(m1) < 35 || parseInt(m2) < 35 || parseInt(m3) < 35){
$("#result").val("Fail");
}
else{
$("#result").val("Pass");

PHP (Hypertext PreProcessor) P a g e 213 |


Nandha Arts and Science College PHP – V Unit BCA Department

$("#total").val(total);
$("#avg").val(avg);
}

</script>
<br><br>
<table border="1">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Mark3</th>
<th>Total</th>
<th>Average</th>
<th>Result</th>
</tr>
<?php
$query = "SELECT * FROM m1";
$res = mysqli_query($db,$query);
$row = mysqli_num_rows($res);
$i = 1;
if($row > 0) {
while($list = mysqli_fetch_assoc($res)){
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $list['name']; ?></td>
<td><?php echo $list['m1']; ?></td>
<td><?php echo $list['m2']; ?></td>
<td><?php echo $list['m3']; ?></td>
<td><?php echo $list['total']; ?></td>
<td><?php echo $list['avg']; ?></td>
<td><?php echo $list['result']; } } ?></td>
</tr>
</table>
</body>
<html>

---x---x---x---

PHP (Hypertext PreProcessor) P a g e 214 |


General Topic (Scripting & PHP Languages)

Page | 1
Difference between PHP and JavaScript
PHP and JavaScript both are used for different purposes. As we have discussed earlier that PHP is a server-side
script, whereas, JavaScript is a client-side script. Below are some differences between PHP and JavaScript has
given:

PHP JavaScript

PHP is a server-side scripting language. JavaScript is a client-side scripting language.

PHP performs all the server-side functions like JavaScript is designed to create an interactive
authentication, building custom web content, web application without interacting with the
handling request, etc. server

PHP can combine with HTML only. JavaScript can combine with HTML, AJAX and
also with XML.

PHP is used for back-end purpose only. JavaScript is used for both front-end and back-
end.

PHP is easy to learn. JavaScript is complex to learn.

PHP is a multi-threadedlanguage, which means it JavaScriptis single-threaded, i.e.,event-driven,


blocks input/output to do multiple tasks which means it never blocks, and everything
concurrently. runs in concurrent order.

In PHP, the code will be available and viewed after A JavaScript code can be viewed Even after the
it is interpreted by the server. output is interpreted.

It is synchronous by nature and waits for I/O JavaScript is asynchronous by nature and does
operation to execute. not wait for I/O operation to execute.

Page | 2
Which are scripting languages?
A scripting or script language is a programming language that supports scripts; programs written for a
special run-time environment that automate the execution of tasks that could alternatively be executed
one-by-one by a human operator.

What is the difference between a scripting language and a programming language?


The theoretical difference between the two is that scripting languages do not require the compilation step
and are rather interpreted. For example, normally, a C program needs to be compiled before running
whereas normally, a scripting language like JavaScript or PHP need not be compiled.

List of Scripts language

AppleScript Lua Rexx


ColdFusion m4 Ruby
DCL Modern Pascal Scheme
Embeddable Common Lisp Perl Tcl
ecl PHP Unix Shell scripts (ksh, csh,
Erlang PowerShell bash, sh and others)
JCL Pure VBScript
CoffeeScript Python Work Flow Language
JavaScript Rebol XSLT
JScript Red x

XML
XML stands for Extensible Markup Language and is a text-based markup language derived from Standard
Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying how to
display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near
future, but it introduces new possibilities by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and solutions

Page | 3
XML is extensible − XML allows you to create your own self-descriptive
tags, or language, that suits your application.
XML carries the data, does not present it − XML allows you to store the data irrespective of how
it will be presented.
XML is a public standard − XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available
as an open standard.

What is XML?
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data
• XML was designed to be self-descriptive
• XML is a W3C Recommendation

XML Does Not DO Anything


Maybe it is a little hard to understand, but XML does not DO anything.
This note is a note to Tamil from Janu, stored as XML:
<note> Note
<to>Tamil</to> To: Tamil
From: Janu
<from>Janu</from>
Reminder
<heading>Reminder</heading> Don't forget me this
<body>Don't forget me this weekend!</body> weekend!

</note>

The XML above is quite self-descriptive:


• It has sender information.
• It has receiver information
• It has a heading
• It has a message body.
But still, the XML above does not DO anything. XML is just information wrapped in tags. Someone must
write a piece of software to send, receive, store, or display it:

Page | 4
The Difference between XML and HTML
XML and HTML were designed with different goals:
• XML was designed to carry data - with focus on what data is
• HTML was designed to display data - with focus on how data looks
• XML tags are not predefined like HTML tags are

XML Does Not Use Predefined Tags


The XML language has no predefined tags.
The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags
are "invented" by the author of the XML document. HTML works with predefined tags like <p>, <h1>,
<table>, etc. With XML, the author must define both the tags and the document structure.

XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).
Imagine an application designed to display the original version of note.xml (<to> <from> <heading>
<data>). Then imagine a newer version of note.xml with added <date> and <hour> elements, and a
removed <heading>. The way XML is constructed, older version of the application can still work:
<note>
Old Version
<date>2015-09-01</date> Note
<hour>08:30</hour> To: Tamil
From: Janu
<to>Tamil</to> Head: (none)
<from>Janu</from> Don't forget me this weekend!

<body>Don't forget me this weekend!</body>


</note>
XML Simplifies Things New Version
• It simplifies data sharing Note
To: Tamil
• It simplifies data transport From: Janu
• It simplifies platform changes Date: 2015-09-01 08:30
Don't forget me this weekend!
• It simplifies data availability
XML Usage
A short list of XML usage says it all −
✓ XML can work behind the scene to simplify the creation of HTML documents for large web sites.
✓ XML can be used to exchange the information between organizations and systems.

Page | 5
✓ XML can be used for offloading and reloading of databases.
✓ XML can be used to store and arrange the data, which can customize your data handling needs.
✓ XML can easily be merged with style sheets to create almost any desired output.
✓ Virtually, any type of data can be expressed as an XML document.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that is both human-
readable and machine-readable. So what exactly is a markup language? Markup is information added to
a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate
to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>...
</text>. The tags <message> and </message> mark the start and the end of the XML code fragment. The
tags <text> and </text> surround the text Hello, world!.
Is XML a Programming Language?
A programming language consists of grammar rules and its own vocabulary which is used to create
computer programs. These programs instruct the computer to perform specific tasks. XML does not
qualify to be a programming language as it does not perform any computation or algorithms. It is usually
stored in a simple text file and is processed by special software that is capable of interpreting XML.
The following diagram depicts the syntax rules to write different types of markup and text in an XML
document. Let us see each component of the above diagram in detail.
aXML Declaration
The XML document can optionally have an XML declaration. It
is written as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the
character encoding used in the document.

Page | 6
Syntax Rules for XML Declaration
• The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in lower-case.
• If document contains XML declaration, then it strictly needs to be the first statement of the XML document.
• The XML declaration strictly needs be the first statement in the XML document.
• An HTTP protocol can override the value of encoding that you put in the XML declaration.
Tags and Elements
An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The names of
XML-elements are enclosed in triangular brackets < > as shown below −
<element>
Syntax Rules for Tags and Elements
Element Syntax − Each XML-element needs to be closed either with start or with end elements as
shown below −
<element>....</element>
or in simple-cases, just this way −
<element/>
Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the
children elements must not overlap. i.e., an end tag of an element must have the same name as that of
the most recent unmatched start tag.
The Following example shows incorrect nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>Tutorials
<contact-info>
</company>
The Following example shows correct nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPHP</company>
<contact-info>
Root Element − An XML document can have only one root element. For example, following is not a correct
XML document, because both the x and y elements occur at the top level without a root element
<root>

Page | 7
<x>...</x>
<y>...</y>
</root>
Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the start and
the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>
XML Attributes
An attribute specifies a single property for the element, using a name/value pair. An XML-element can
have one or more attributes. For example −
<a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a>
Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value.
Syntax Rules for XML Attributes
• Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered
two different XML attributes.
• Same attribute cannot have two values in a syntax. The following example shows incorrect
syntax because the attribute b is specified twice
<a b = "x" c = "y" b = "z">....</a>
• Attribute names are defined without quotation marks, whereas attribute values must always
appear in quotation marks. Following example demonstrates incorrect xml syntax
<a b = x>....</a>
XML References
References usually allow you to add or include additional text or markup in an XML document.
References always begin with the symbol "&" which is a reserved character and end with the symbol
";". XML has two types of references −
Entity References − An entity reference contains a name between the start and the end delimiters. For
example &amp; where amp is name. The name refers to a predefined string of text and/or markup.
Character References − These contain references, such as &#65;, contains a hash mark (“#”) followed by
a number. The number always refers to the Unicode code of a character. In this case, 65 refers to
alphabet "A".

Page | 8
AJAX
AJAX is a developer's dream, because
you can:
• Update a web page without reloading
the page
• Request data from a server - after the
page has loaded
• Receive data from a server - after the
page has loaded
• Send data to a server - in the
background
What is AJAX?
✓ AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
✓ Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
✓ Conventional web applications transmit information to and from the server using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
✓ With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results,
and update the current screen. In the purest sense, the user would never know that anything was
even transmitted to the server.
✓ XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
✓ AJAX is a web browser technology independent of web server software.
✓ A user can continue to use the application while the client program requests information from
the server in the background.
✓ Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.
✓ Data-driven as opposed to page-driven.

Page | 9
Rich Internet Application Technology
AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry
momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser
incompatibility and it is supported by JavaScript, which is hard to maintain and debug.
AJAX is Based on Open Standards
AJAX is based on the following open standards:
Browser-based presentation using HTML and Cascading Style Sheets (CSS).
Data is stored in XML format and fetched from the server.
Behind-the-scenes data fetches using XML Http Request objects in the browser.
JavaScript to make everything happen.
AJAX Technologies
AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages.
JavaScript
✓ Loosely typed scripting language.
✓ JavaScript function is called when an event occurs in a page.
✓ Glue for the whole AJAX operation.
DOM
✓ API for accessing and manipulating structured documents.
✓ Represents the structure of XML and HTML documents.
CSS
✓ Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript.
✓ XML HttpRequest
✓ JavaScript object that performs asynchronous interaction with the server.
PHP and AJAX Example
<!DOCTYPE html>
<html> <head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;

Page | 10
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form> First name: <input type="text" onkeyup="showHint(this.value)"> </form>
<p>Suggestions: <span id="txtHint"></span></p> </body> </html>

How Ajax is working?


AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated
asynchronously by exchanging small amounts of data with the server behind the scenes. This means that
it is possible to update parts of a web page, without reloading the whole page.
What is Ajax in programming?
Ajax is a client-side script that communicates to and from a server/database without the need for a
postback or a complete page refresh. The best definition I've read for Ajax is “the method of exchanging
data with a server, and updating parts of a web page – without reloading the entire page.

Page | 11
What is Ajax in JavaScript?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and
more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for
content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content
display.
What is the jquery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal
and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works
across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed
the way that millions of people write JavaScript.
What is Javascript and jquery?
Javascript is a programming language whereas jQuery is a framework to help make writing in javascript
easier. It's particularly useful for simply traversing the DOM in an HTML page.
jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing

CSS
What is CSS?
CSS stands for Cascading Style Sheets
CSS describes how HTML elements are to be displayed on screen, paper, or in other media
CSS saves a lot of work. It can control the layout of multiple web pages all at once
External stylesheets are stored in CSS files
CSS is a language that describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout and variations in
display for different devices and screen sizes.
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>

Page | 12
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large websites, where fonts and color information
were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
CSS Saves a Lot of Work!
The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by changing just
one file!

CSS Syntax
A CSS rule-set consists of a selector and a declaration block:

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
A CSS declaration always ends with a semicolon, and declaration blocks are
surrounded by curly braces.

Example
In this example all <p> elements will be center-aligned, with a red text color:
p {
color: red;
text-align: center;
}

Node.js
Node.js was written initially by Ryan Dahl in 2009, about thirteen years after the introduction of the first
server-side JavaScript environment, Netscape's LiveWire Pro Web. The initial release supported only
Linux and Mac OS X. Its development and maintenance was led by Dahl and later sponsored by Joyent.

Page | 13
ECMAScript
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMAScript is the official name of the language.
From 2015 ECMAScript is named by year (ECMAScript 2015).
ECMA Script History
The ECMAScript specification is a standardized specification of a scripting language developed by Brendan
Eich of Netscape; initially it was named Mocha, later LiveScript, and finally JavaScript. In December 1995,
Sun Microsystems and Netscape announced JavaScript in a press release. The first edition of ECMA-262
was adopted by the ECMA General Assembly in June 1997. Several editions of the language standard have
been published since then. The name "ECMAScript" was a compromise between the organizations
involved in standardizing the language, especially Netscape and Microsoft, whose disputes dominated the
early standards sessions. Eich commented that "ECMAScript was always an unwanted trade name that
sounds like a skin disease." While both JavaScript and JScript aim to be compatible with ECMAScript, they
also provide additional features not described in the ECMA specifications.
Latest June 2018 ECMAScript 2018 (ES2018) 9th Edition
JavaScript vs. ECMA Script
JavaScript
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of
the language has been embedded in Netscape, Internet Explorer, and other web browsers.
The standard of scripting languages like JavaScript is ECMAScript.
ECMAScript
The full form of ECMA is European Computer Manufacturer's Association. ECMAScript is a
Standard for scripting languages such as JavaScript, JScript, etc. It is a trademark scripting
language specification. JavaScript is a language based on ECMAScript. A standard for
scripting languages like JavaScript, JScript is ECMAScript. JavaScript is considered as one of
the most popular implementations of ECMAScript.
• ECMAScript: Sun (now Oracle) had a trademark on the name“JavaScript” (which led to
Microsoft calling its JavaScript dialect “JScript”). Thus, when it came to standardizing the
language, a different name had to be used. Instead, “ECMAScript” was chosen, because
the corresponding standard is hosted by ECMA International (see below). In practice, the
terms “ECMAScript” and “JavaScript” are interchangeable. If JavaScript means

Page | 14
“ECMAScript as implemented by Mozilla and others” then the former is a dialect of the
latter. The term “ECMAScript” is also frequently used to denote language versions (such
as ECMAScript 5).
• ECMA-262: The ECMA International (a standards organization) has created the ECMA-
262 standard which is the official specification of the ECMAScript language.
• ECMA’s Technical Committee 39 (TC39): is the group of people (Brendan Eich and
others) who develop the ECMA-262 standard.
• ECMAScript 3 (December 1999). This is the version of ECMAScript that most browsers
support today. It introduced many features that have become an inherent part of the
language:
• regular expressions, better string handling, new control statements, try/catch
exception handling, tighter definition of errors, formatting for numeric output and
other enhancements.
• ECMAScript 4 (abandoned July 2008). ECMAScript 4 was developed as the next
version of JavaScript, with a prototype written in ML. However, TC39 could not agree on
its feature set. To prevent an impasse, the committee met at the end of July 2008 and
came to an accord, summarized in four points
1. Develop an incremental update of ECMAScript [which became ECMAScript 5.
2. Develop a major new release, which was to be more modest than ECMAScript 4, but much
larger in scope than the version after ECMAScript 3. This version has been code-
named Harmony, due to the nature of the meeting in which it was conceived.
3. Features from ECMAScript 4 that would be dropped: packages, namespaces, early
binding.
4. Other ideas were to be developed in consensus with all of TC39.
• The ECMAScript 4 developers agreed to make Harmony less radical than ECMAScript
4, the rest of TC39 agreed to keep moving things forward.
• ECMAScript 5 (December 2009). This version brings several enhancements to the
standard library and even updated language semantics via a strict mode.
• currently browsers are supporting upto ES5 only.
ECMAScript 6(2015)
• ES6 is an next-gen of JavaScript, the ecma technical committee 39 governs ecma
specification, they discovered new features to the javascript.
• ES6 can`t compile directly in browsers, so need an compiler from ES6 to ES5, for that
compiling using babel, it produce the browser compatible javascript.

Page | 15

You might also like