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

Final Unit 3 2079 Chaitra Full Modified

3

Uploaded by

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

Final Unit 3 2079 Chaitra Full Modified

3

Uploaded by

suchitkhadka56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Unit 3- Web Technology II

Q. Define web technology. What are static and dynamic webpage?


Ans: Web technology is defined as the technology that primarily deals
with how to save web information securely in web servers and how to
retrieve information from these servers using different internet based
tools and techniques. The three main languages which helps to make
the WWW are HTML, CSS and JAVASCRIPT.
Webpage is the collection of electronic documents provided by website
to the user in internet.
A collection of webpage is called website.
Types of web technology:
1. Web browser: Browsers are interpreters of the web. E.g. Google
chrome, Safari, firefox, Internet Explorer etc.
2. HTML: It is a Hyper Text Markup Language. It provides the
structure of a website so that web browsers know what to show.
3. CSS: It is a Cascading Style Sheet. CSS let’s web designers change
colors, fonts, animation and transition on the web. They make the
web look good.
4. Programming language: Programming languages are ways to
communicate to computer and tell them what to do.
a. Javascript: It is used by all web browser, meteor, and lost of
other frameworks.
b. Python: It is used by the Django framework and used in a lot of
mathematical calculations.
c. Ruby: It is used by the Ruby on Rails framework.
d. PHP: It is used by wordpress.
e. Objective-C: This is the programming language behind iOS, lead
by Apple.
f. Swift: Apple’s newest programming language.
g. Java: It is used by Android and a lots of desktop apps.
5. Frameworks: Framework are built to make and working with
programming languages easier.
a. Metero: It is a full-stack javascript framework.
b. Node.js: It is a server-side javascript framework.
c. Ruby on Rails: It is full-stack framework built by Ruby.
d. Django: It is full-stack framework build using Python.
e. Bootstrap: It is a framework for building with HTML/CSS/
Javascript.
f. .NET: It is a full-stack framework built by Microsoft.
6. Database: Database are where all your data is stored. E.g.
MongoDB, Redis, PostgreSQL, MySQL, Oracle, SQL server etc.
7. Client: It is one user of an application.
8. Server: It is where the application code is typically stored.
9. API: It is an Application Programming Interface.
10. Data formats: Data formats are the structure of how data are
stored. Eg JSON, XML, CSV.
Q. Differences between client side scripting and server side scripting.
Ans:
Q. Why script is importance in web programming?
Ans: Script is importance in web programming because scripting
languages are widely used and in demand due to its capability to
produce dynamic content specially in web-based applications. A
scripting language allows users to develop dynamic and interactive
web pages with minimum effort and less programming skill.
Q. Write about internet technology.
Ans: The term ‘internet’ comes from the word computer network.
When one computer network connects to other computer
networks then, it becomes internet. The internet is defined as a
global system of interconnection of millions of networks around
the world that use common standard rules, commonly known as
TCP/IP ( Transmission Control Protocol/ Internet Protocol). HTTP is
a set of rules to transfer the WebPages with hyperlinks that can be
viewed on web browser such as Microsoft Edge, Google Chrome,
Safari etc. Software download for Javascript Editor:
Free Javascript Editor 4.7, Notepad++, VS code, Sublime text, Atom.io etc.
For Online Code: www.w3schools.com
Adding Java Script to HTML page:
You can use JavaScript code in two ways:
1. You can either include the javascript code internally within your
HTML document itself.
2. You can keep the javascript code in a separate external file and
then point to that file from your HTML document.

Adding Javascript internally:


To add the javascript code into the HTML pages, we can use
<script>……….</script> tag of the HTML that wrap around javascript
code inside the HTML program. User can also define javascript code in
the <body> tag or we can say body section or <head> tag.
Example:
<!DOCTYPE html>
<html>
<head><title> Adding Javascript Internally</title>
<script>
document.write(“Welcome to Java”);
</script>
</head>
<body>
<p> In this example we saw how to add javascript in the head section.
</p>
</body>
</html>

Adding javascript in externally:


We can also create a separate file to hold the code of javascript with the
(.js) extension and later incorporate/include it into HTML document
using the src attribute of the <script> tag. It is very helpful if we want to
use the same code in multiple HTML documents. It also saves us from
the task of writing the same code over and over again and makes it
easier to maintain web pages.
<html>
<head>
<meta charset="utf-8">
<title> Include external file</title>
</head>
<body>
<h2>Welcome to Java</h2>
</body>
<script src="hello.js">
</script>
</html>

Now Let’s create separate Javascript file


hello.js
document.write("I love javascript");
JavaScript can "display" data in different ways:
•Writing into an HTML element, using innerHTML.
document.getElementById(“demo”).innerHTML=x;
•Writing into the HTML output using document.write().
document.write(“Hello Java”);
•Writing into an alert box, using window.alert().
window.alert(“Welcome to Java”); or alert(“SPA”);
•Writing into the browser console, using console.log().
console.log(“I love Java”);

4 Ways to Declare a JavaScript Variable:


•Using var
•Using let
•Using const
•Using nothing
Example :2

In HTML Doc In JS Doc (GFG.JS)


<!DOCTYPE html>
<html> let h2 = document.querySelector(".external");
h2.addEventListener("mouseenter", function (e)
<head> {
<title>External JavaScript</title>
h2.innerText = "Thank you";
<style>
h2 { });
box-sizing: border-box;
width: 250px;
height: 150px;
background-color: blue;
color: white;
margin: auto;
font-size: 15px;
font-family: sans-serif;
text-align: center;
padding: 20px;
}
</style>
</head>

<body>
<h2 class="external">Hello Java</h2>
<script src="GfG.js"></script>
</body>

</html>
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

</body>
</html>
Java Script Fundamental:
About Java Script:
Javascript (“JS” for short) is a full-fledge dynamic programming language
that can add interactivity to a website. It was invented by Brendan Eich
(co-founder of the Mozilla project, the Mozilla Foundation and the
Mozilla Corporation). It is implemented as client-side script in html to
make dynamic website.
When JavaScript was created, it initially had another name: “LiveScript”.
The different languages work together to enable the creation of modern
web pages:
1. HTML to define the content such as text, image, links of web pages.
2. CSS to specify the layout or style of web pages.
3. JavaScript to program the behavior of web pages.
Features of Javascript
1. It is standard scripting language and supported by most of the
browser.
2. It is client-side technology.
3. JavaScript provides greater control to the browser rather than
being completely dependent on the web servers.
4. It can run on Windows, Macintosh, and other Netscape-
supported systems.
5. JavaScript has built-in functions to determine the date and
time. Thus it is very easy to code only by using methods
like .getDate().
6. It is open source and cross platform ( also called multi-
platform software).
Importance/use of Javascript
Simple user interaction function:
Javascript provides 3 built-in function to do simple user
interaction:
•alert(msg): It helps to make alerts to the user that something
has happened.
Example:
alert(“Don’t touch it hot”);
•confirm(msg): It helps to ask the user to confirm or cancel
something.
Example:
confirm(“do you want to delete the file”);
•prompt(msg, default value): It helps to ask user to enter some
text value.
Example:
prompt(“Enter your name”,”Arun”);
<!doctype html>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
document.write("Example of alert, confirm and prompt");
alert("Thanks for visiting");
confirm("Do you want to delete the file");
prompt("Enter your name",“Arun");
</script>
</body>
</html>
Javascript data types:
Every programming language has set of data types. Javascript provides
3 basic types of data types i.e number(+-(0-9)), string(“Dharma”) and
Boolean (true or false).
•number= -15, 200,-35.44, 578.40 etc
•String= “A”, ”a”, “ABC”, “9858420004”, “Example of string”.
•Boolean= true or false or 0 or 1 or yes or no.

Moreover, javascript also provides two trivial or unimportant data


types called null and undefined. Such data types only a single value.
•Null : let age=null;
•Undefined: let a;
var a;
console.log(a); //This will return undefined.
And var a=5;
console.log(a); // This will return 5.
Variable and operators:
A variable defines a unique name that represents a unit of
memory space to store data on computer.
Rules of variable naming in Javascript:
a. A variable name must starts with letter, underscore (_ ), or
dollar sign( $ ).
b. Names can also begin with $ and _ (but we will not use it)
c. A variable name cannot start with number.
d. A variable name can only contain alpha-numeric characters
(a-z, 0-9) and underscores.
e. Javascript variables are case sensitive, for e.g. a and A are
different variable.
f. A variable name cannot contain spaces.
g. A variable name cannot be a javascript keywords or reserved
word.
A variable should declare before using it, so it is declared by
using keyword or reserved word var or let followed by
semicolon (;).
Var: It is used to declare variable. You can assign a value to a
variable using equal or assignment (=) operator.
Syntax:
var variable_name; //without value
var variable_name=value; // with value

E.g.
Var a; // without assigning value
Var g=‘Apple’; //store string value
Var x=10; // store numeric value
Var a,g=“apple”,x=10; // multiple variables can also
declared in a single line separated by comma.
Let: The let statement is used to declare a local variable in
javascript. It is similar to the keyword var but let keyword
can enhance our code readability and decreases the chances
of programming error.
Syntax:
Let variable_name;
Let variable_name=value;

E.g.
Let a; //undefined
Let name=“Arun”;
Let x=10;
Let a=3,b=5.5,c=44;
<!DOCTYPE html>
<html>
<head>
<title>Example </title>
</head>
<body>
<script type="text/javascript">
var a=55;
document.write("The value of a is "+a);
</script>
</body>
</html>

Output is:
The value of a is 55
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<p id="demo"></p>
<script type="text/javascript">
var x=100;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output:
100
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arithmetic</h2>
<p>A typical arithmetic operation takes two numbers (or variables) and produces
a new number.</p>

<p id="demo"></p>

<script>
let a = 100;
let b = 50;
let x = a + b;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>
<p id="price"></p>

<script>
let person = "John Doe“,carName = "Volvo“,price = 200;
document.getElementById("demo").innerHTML = carName;
document.getElementById("price").innerHTML = price;
</script>

</body>
</html>
Q. Write a JavaScript to add any two numbers.
<!DOCTYPE html>
<html>
<head>
<title>Add to numbers </title>
</head>
<body>
<script type="text/javascript">
var a=55,b=10,sum; //variable declaration
sum=a+b;
document.write("The sum of two numbers is "+sum); //display output
}
</script>
</body>
</html>

Output is:
The sum of two numbers is 65
Q. Write a JavaScript to add two number entered by user.

<!DOCTYPE html>
<html>
<body>
<script>
let a = parseInt(prompt("Enter the first number ")); //input first value
Let b = parseInt(prompt("Enter the second number "));

//add two numbers


let sum = a + b;

// display the sum


document.write("The sum is "+sum);
</script>
</body>
</html>
Q. Write a JavaScript to add any two numbers.
<!DOCTYPE html>
<html>
<body>
<h2>Add two numbers</h2>
<p id="add"></p> //element
<script>
let a = 100;
let b = 50;
let x = a + b;
document.getElementById("add").innerHTML =("The sum of two numbers is ")+x;
</script>
</body>
</html>

Output is:
The sum of two numbers is 150
Example array:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

Output:
Saab, Volvo,BMW
Const : Variable can be declared using const similar to var or
let declaration. The const makes a variable a constant where
its value cannot be changed.
Example:
Const height=5.5; //ok
Height=5.5; // type error
Operator
Operator are symbols that tell the javascript engine to
perform some type of action. The following sections
describe the different operators used in javascript.
1. Arithmetic 5. Special (?:, comma, void,……)
2. Comparison 6. String or concatenation (+)
3. Logical 7. Bitwise (<<, >>, &, |,…..)
4. Assignment 8. Ternary (a>b?a:b; )
1. Arithmetic Operator:
Operator Description Example
+ Addition 10+20=30
- Subtraction 20-10=10
* Multiplication 10*20=10
/ Division 20/10=2
% Modulus(Remainder) 9%4=1
++ Increment Var a=10; a++; a=11
-- Decrement Var a=10; a--; a=9

2. Comparison Operator:
Operator Description Example
< Less than A<b
<= Less than equal to A<=b
> Greater than A>b
>= Greater than equal A>=b
== Equal to A==b
!= Not equal to A!=b
3. Logical Operator:
Operator Description Example
&& Logical AND A&&b
|| Logical OR A||b
! Logical NOT !a

4. Assignment Operator:
Operator Description Example
== Assignment A==1
+= Add and assignment A+=5 // a=a+5
-= Subtract and assignment A-=5 //a=a-5
*= Multiply and assignment A*=5 // a=a*5
/= Divide and assignment a/=5 // a=a/5
%= Modulus divide and assignment A%=5 //a=a%5
<!doctype html>
<html>
<head>
<title>Example of operator</title>
</head>
<body>
<script type="text/javascript">
var a=55;
var b=7;
var result;
document.write("a=55 <br> b=10 ");
result=a+b;
document.write("<br>a+b="+result);
result=a-b;
document.write("<br>a-b=",+result);
result=a/b;
document.write("<br><br>a/b="+result);
result=a%b;
document.write("<br>a%b="+result);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Assignments</h2>
<h3>The += Operator</h3>
<p id="demo"></p>
<script>
let x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Control structure and Function
( if…else, if….elseif, switch case, for, while and do while loop)
Control Statements:
Control statements are designed to allow you to create script that can
decide which line of code are evaluated, or how many times to
evaluate them. There are two types of control statements: Conditional
and iteration or loop statements.
a. Conditional Statements: Conditional statements result in either
true or false.
i. If statement: If statements are used for the purpose of decision
making; they evaluate the statement if the condition is true
otherwise the condition is false to exit.
Syntax:
If(condition)
{
Statement; // given condition is true to execute the statement.
}
<!DOCTYPE html>
<html>
<head>
<title> if statement</title>
</head>
<body>
<script type="text/javascript">
let p=prompt("Enter your marks","1-100");
if(p>=40)
document.write("You are passed");
</script>
</body>
</html>
ii. If…..else statement: This is the simple form of conditional statement
in which statements are executed based on given condition. When
condition is true, first statement is executed otherwise the second
statement is executed.
Syntax:
If(condition)
{
True Statement;
}
Else
{
False Statement;
}
<!DOCTYPE html>
<html>
<head>
<title> if statement</title>
</head>
<body>
<script type="text/javascript">
let p=prompt("Enter your marks","1-100");
if(p>=40)
document.write("You are passed");
else
document.write(“you are failed”);
</script>
</body>
</html>
iii. If…else if statement: When we have two or more conditions to be
checked in a series we can use if-else if statement. This is ladder
type f if else conditional statement in which statements are
executed based on multiple given conditions.
Syntax:
If(condition1) else
{ {
True Statement; last statement;
} }
Else if(condition2)
{
second Statement;
}
Else if(condition3)
{
Third statement;
}
…………………………
<!DOCTYPE html>
<html>
<head><title>if else if</title></head>
<body>
<script type="text/javascript">
var a=prompt("Enter any number");
if(a>0)
{
document.write("The number is positive");
}
else if(a<0)
{
document.write("The number is negative");
}
else
{
document.write("The number is zero");
}
</script>
</body>
</html>
iv. switch statement: When a program flow of given problem is divided
into multi-path statement then we can apply switch case
statement. It selects the case based on the value of expression of
the switch statement.
Syntax:
Switch(expression)
{
Case “1”: statement;
break;
Case “2”: statement;
break;
…………………………….
…………………………….
Case “n”: statement;
break;
Default:
Default statement;
}
<!DOCTYPE html>
<html>
<head>
<title>if else if</title>
</head>
<body>
<script type="text/javascript">
var day=prompt("Enter a number","1-7");
switch(day)
{
case "1": document.write("Sunday");
break;
case "2": document.write("Monday");
break;
case "3": document.write("Tuesday");
break;
case "4": document.write("Wednesday");
break;
case "5": document.write("Thursday");
break;
case "6": document.write("Friday");
break;
case "7": document.write("Saturday");
break;
default:
document.write("Wrong choice! Enter 1-7");
}
</script>
</body>
</html>

•Looping or iteration
Looping is the process of executing the same program statement or block of program
statements repeatedly for specified number of times or until the given condition is
satisfied.
3 types of loop:
a. For loop
b. While loop
c. Do..while loop
a. For loop: The for loop is most used loop in programming. The
initialization, condition and counter are defined at the same line within
the loop. These expression are separated by semicolon.
Syntax:
for( initialization; condition; counter)
{
Statement
}

b. While loop: In while loop, it checks condition at first; if it is found true then
it executes the statements written in its body part otherwise it just gets
out from the loop structure. It is entry control or pre-test loop.
Syntax:
Initialization;
While(condition)
{
Statement;
Counter;
}
c. do….while loop : In do….while loop, it executes the statements written
inside body once if the condition is false and finally checks the condition.
It is similar to while loop. It is also called exit control or post test loop.
Syntax:
Initialization;
do
{
Statement;
Counter;
} While(condition);

Example
Q. Write a javascript to display natural number from 1 to 10 using for, while
and do while loop.
Q. Write a JavaScript to display Fibonacci series.
Q. Write a JavaScript to input any number from user then display its Factorial.
Q. Write a JavaScript to input any number then display sum of each digits.
For loop While loop
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>loop example</title> <title>loop example</title>
</head> </head>
<body> <body>
<script type="text/javascript"> <script type="text/javascript">
var i; var i=1;
for(i=1;i<=10;i=i+1) while(i<=10)
{ {
document.write("<br>"+i); document.write("<br>"+i);
} i=i+1;
</script> }
</body> </script>
</html> </body>
</html>
Do…while loop
<!DOCTYPE html>
<html>
<head>
<title>loop example</title>
</head>
<body>
<script type="text/javascript">
var i=1;
do
{
document.write("<br>"+i);
i=i+1;
} while(i<=10);
</script>
</body>
</html>
Q. Write a JavaScript to display Fibonacci series.
2 2 4 6 10 ……..upto 12th
</DOCTYPE html>
<html>
<head>
<title>fibonacci series</titel>
</head>
<body>
<script type=“text/javascript”>
let a=2, b=2, c, i;
document.write(“ ” + a);
document.write(“ ”+ b);
for(i=1;i<=10; i=i+1)
{
c=a+b;
document,.write(“ ”+c);
a=b;
b=c;
}
</script>
</body>
</html>
Write a JavaScript to input any number from user then display its Factorial
</DOCTYPE html>
<html>
<head>
<title>factorial</titel>
</head>
<body>
<script type=“text/javascript”>
let n=parseInt(prompt(“Enter any number”));
let f=1,i;
for(i=n;i>=1;i=i-1)
{
f=f*i;
}
document,.write(“The factorial number is”+f);
</script>
</body>
</html>
Q. Write a JavaScript to input any number then display sum of each digits.

</DOCTYPE html>
<html>
<head>
<title>sum of digits</titel>
</head>
<body>
<script>
let n= parseInt(prompt(“Enter any number”));
let s=0;
while (n!=0)
{
r=n%10; or s+=n%10;
s=s+r;
n= Math.floor(n/10);
}
document.write(“The sum of digit is”+s);
</script>
</body>
</html>
Q. Write a JavaScript to display 1 to nth term prime number entered by user.
<html>
<head>
<title>Prime number nth term</title>
</head>
<body>
<script>
let i,j;
let n=parseInt(prompt("Enter number"));
for(i=2;i<=n;i++)
{
for(j=2;j<=i;j++)
{
if(i==j)
{
document.write(" "+i);
}
else if (i%j==0)
{
break;
}
}
}
</script>
</body>
</html>
Function in Java Script
Functions are one of the fundamental(primary) building blocks in java
script. A function is a block of code which will execute only if it is
called.
Declaration of Function:

Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();
Example of Function:

<!DOCTYPE html>
<html>
<head><title> Function</title></head>
<body>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
};
myFunction();
</script>
</body>
</html>
Q. Write a function to add any two numbers using javascript.
<!DOCTYPE html>
<html>
<head>
<title>Add to numbers using function </title>
</head>
<body>
<script type="text/javascript">
function add()
{
var a=55,b=10,sum; //variable declaration
sum=a+b;
document.write("The sum of two numbers is "+sum); //display output
}
add(); //function call
</script>
</body>
</html>

Output is:
The sum of two number is 65
Q. Write a function to add any two numbers using javascript.
<!DOCTYPE html>
<html>
<head>
<title>Add to numbers using function </title>
</head>
<body>
<script type="text/javascript">
function add(a,b)
{
var a,b,sum; //variable declaration
sum=a+b;
document.write("The sum of two numbers is "+sum); //display output
}
add(5,6); //function call
</script>
</body>
</html>

Output is:
The sum of two number is 11
Q. Write a function to product any two numbers using javascript.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b)
{
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

Output:
Javascript Function
This example calls a function which performs a calculation, and returns the result:
12
Q. Write a Javascript to add two number from user then display its sum using function and form.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add two number</title> Q. Write a JavaScript to input principal amount, rate
</head> and time from user then display simple interest
<script> Using function and form.
function add()
{
var a,b,s;
a=parseInt(document.getElementById("first").value);
b=parseInt(document.getElementById("second").value);
s=a+b;
document.getElementById("answer").value=s;
}
</script>
<body>
<p>Enter first number:<input id="first"></p>
<p>Enter second number:<input id="second"></p>
<button onclick="add()">Sum</button>
<p>Sum=<input id="answer"></p>
</body>
</html>
Q. Write a Javascript to show the example of tofixed() method.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add two number</title>
</head>
<body>
<p id=“demo”></p>
<script>
let num=5.3454;
let n=num.tofixed(2);
document.getElementById(“demo”).innerHTML=n;
</script>
</body>
</html>
Object Based Programming with Java Script

In JavaScript, objects are king. If you understand objects, you


understand JavaScript.

In JavaScript, almost "everything" is an object.


•Booleans can be objects (if defined with the new keyword)
•Numbers can be objects (if defined with the new keyword)
•Strings can be objects (if defined with the new keyword)
•Dates are always objects
•Maths are always objects
•Regular expressions are always objects
•Arrays are always objects
•Functions are always objects
•Objects are always objects
Create a new object in JavaScript by setting its properties inside curly
braces.
<!DOCTYPE html>
<html>
<body> The named values, in JavaScript objects, are called properties.

<h2>JavaScript Objects</h2>
<p>Creating an object:</p>

<p id="demo"></p>

<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};

document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;


</script>

</body>
</html>
An object method is an object property containing a function definition.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
function() {return this.firstName + " " +
fullName
this.lastName;}

What is this?
In JavaScript, the this keyword refers to an object in which object
depends on how this is being invoked (used or called). Methods like
call(), apply(), and bind() can offer this to any object. This is not a variable
. It is a keyword. You cannot change the value of this. When used alone,
this refers to the global object.
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
Event handling
Event Handling/Document Object Model (DOM): Any action that user
performs on a web page is known as an event like moving of mouse,
clicking button, clicking a link, text input, selection or even loading a
page.
Event handlers can be used directly within HTML elements by using
special attributes. The event handlers can also be used within
<script>….</script> tags or in an external JavaScript file.
The delegation(assignment/action) event model has the following key
participants namely:
Source: A source is an object that generates an event. Source is
responsible for providing information of the occurred event to it's
handler. Button, Checkbox, Choice, List, Menu Item, Scrollbar, Text
Components, Window .
•Listener : It is also known as event handler or object. Listener is
responsible for generating a response to an event.
What is the DOM?
The DOM defines a standard for accessing documents:
"The WWW Document Object Model (DOM) is a platform and
language- neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a
document."
The W3C DOM standard is separated into 3 different parts:
•Core DOM - standard model for all document types
•XML DOM - standard model for XML documents
•HTML DOM - standard model for HTML documents (Most used)
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<h2>JavaScript HTML Events</h2> <html>
<p>Click the button to display the date.</p> <body>
<button onclick="displayDate()">The time
<h2>JavaScript HTML
is?</button> Events</h2>
<h2
<script>
function displayDate() {
onclick="this.innerHTML='Ooop
document.getElementById("demo").innerHTML = s!'">Click on this text!</h2>
Date(); </body>
}
</script>
</html>

<p id="demo"></p>

</body>
</html>
Event Handler
Event Performed Event Handler Description
click onclick When mouse click on an
element
mouseover onmouseover When the cursor of the mouse
comes over the element
mouseout onmouseout When the cursor of the mouse
leaves an element
mousedown onmousedown When the mouse button is
pressed over the element
mouseup onmouseup When the mouse button is
released over the element
mousemove onmousemove When the mouse movement
takes place.
Keyboard events:

Event Performed Event Handler Description


Keydown & onkeydown & When the user press and
Keyup onkeyup then release the key

Form events:

Event Performed Event Handler Description


focus onfocus When the user focuses on an
element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a


form element

change onchange When the user modifies or


changes the value of a form
element
Window/Document events

Event Event Handler Description


Performed
load onload When the browser finishes the
loading of the page

unload onunload When the visitor leaves the current


webpage, the browser unloads it

resize onresize When the visitor resizes the window


of the browser
• clickevent()
<html>
<head> Javascript Events </head>
<body>
<br>
<br>
<script language="Javascript" type="text/Javascript">

function clickevent()
{
document.write("I am a student of class 12.");
}

</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?">
</form>
</body>
</html>
•mouseoverevent()
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">

function mouseoverevent()
{
alert("This is JavaTpoint");
}

</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
•Focus Event()
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()">
<script>

function focusevent()
{
document.getElementById("input1").style.background="
green";
}

</script>
</body>
</html>
•Keydown Event()
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}

</script>
</body>
</html>
•Load event()
<html>
<head>Javascript Events</head>
<br>
<body onload="window.alert('Page successfully loaded');">
<script>

document.write("The page is loaded successfully");

</script>
</body>
</html>
JavaScript addEventListener()
Syntax
element.addEventListener(event, function, useCapture or bubbling (default));

Although it has three parameters, the parameters event and function are widely used. The
third parameter is optional to define (TRUE or FALSE value).
Example: It is a simple example of using the addEventListener()
method. We have to click the given HTML button to see the effect.
<!DOCTYPE html>
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun()
{
document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome
to the javaTpoint.com";
}
</script>
</body>
</html>
Example
In this example, we are adding multiple events to the same element.
<!DOCTYPE html>
<html>
<body>
<p> This is an example of adding multiple events to the same element. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<p id = "para1"></p>
<script>
function fun()
{
alert("Welcome to the javaTpoint.com");
}

function fun1() {
document.getElementById("para").innerHTML = "This is second function";

}
function fun2() {
document.getElementById("para1").innerHTML = "This is third function";
}
var mybtn = document.getElementById("btn");
mybtn.addEventListener("click", fun);
mybtn.addEventListener("click", fun1);
mybtn.addEventListener("click", fun2);
</script>
</body>
</html>
Server side scripting using PHP
Server side scripting is a method of designing websites. They are
generally used to create dynamic web pages. So, server side scripts
are blocks of program code that execute on a web server computer.
PHP, ASP, JAP, Python, Pearl, Ruby are the example of server side
scripting.
•PHP is a server side scripting language that is embedded in HTML.
•It is used to manage dynamic content, database, ecommerce etc.
•It is integrated with a number of popular databases, including MySQL,
Oracle, Sybase, Informix and Microsoft SQL server.
•PHP supports a large number of protocols such as POP3.
Introduction to PHP (Personal Home Page or Hypertext Preprocessor)
PHP originally stood for Personal Home Page. When any person
request for any PHP page in the address bar of the browser that
request is first sent to the server then server interpret PHP files and
return back response in the form of HTML. That’s why it is called
Hypertext Preprocessor. Rasmus Lerdorf release the first version of
PHP in 1994.
Features of PHP:
•This syntax of PHP is similar to C, So it is easy to learn and use.
•PHP runs on the server side.
•PHP is free software(Open Source Software). We can easily download
it from the official PHP website.
•PHP runs on various platforms like Window, Linux, UNIX, Mac OS etc.
•PHP supports wide range of database.
•PHP is an object oriented language.

Common uses of PHP:


•By using PHP, you can create, open, read, write and close files.
•PHP handle forms.
•You add, delete and modify elements within your database through
PHP.
•Using PHP, you can restrict users to access some pages of your
website.
•It can encrypt data.
PHP files:
PHP file can contain text, HTML, CSS, JavaScript and PHP code. PHP
code is executed on the server side, and the result is returned to
browser as plain HTML. PHP files have extension.php.

Hardware Requirement:
a. 1GHZ CPU or processor
b. 2 GB RAM
c. 1 GB Hard disk
Software Requirement:
• OS: Linux, Unix, Windows, Mac
• Web server(E.g. Apache)
• PHP (Interpreter)
• Database: MySQL5.1 or above(optional), MariaDB 10.0
• Web browser: Internet explorer, Mozilla, Firefox, Google Chrome,
Apple Safari.
• Internet connection
You can separately install Web server, PHP interpreter and MySQL
database, but to make work easier developers have made all in one
setup package called WAMP ( Microsoft window OS Apache MySQL,
PHP), LAMP (Linux OS Apache MySQL PHP), AMPPS, MAMP (Mac OS
Apache MySQL PHP) and XAMPP( X-OS-cross OS Apache MySQL PHP
Perl).
Object oriented programming with server side
scripting:
OOP is a type of programming language that helps in building complex,
reusable web apps. OOP languages like JAVA, PHP, Python and ASP
which are used for server side scripting having following concepts.
A class defines the properties and methods of a real world object. An
object is an occurrence(event) of a class.
The 3 basic components of object oriented are:
a. Object oriented analysis- Functionality of the system.
b. Object oriented designing- architecture of the system.
c. Object oriented programming- implementation of the apps.

PHP is an object oriented scripting language; it supports all of the above


principles. The above principles are achieved through:
• Encapsulation : via the use of “get” and “set” method etc.
• Inheritance: via the use of “extends” keyword.
• Polymorphism: via the use of “implements” keyword.
Basic PHP syntax:
The structure which defines PHP computer language is called PHP
syntax. The PHP script is executed on the server and the HTML result
is sent to the web browser. It can normally have HTML and PHP tags.
PHP files are saved with the “.php” extension. PHP scripts cab be
written anywhere in the document within PHP tags along with normal
HTML.
All PHP codes goes between the php tag. It starts with <?php and ends
with ?>.
The syntax of PHPtag:

<?php
//php code here……
?>
Name of website for building web pages.
Learn HTML

https://www.W3Schools.com/

<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters."; or used .
?>
</body>
</html>
Rules of PHP syntax:
•All the php code in a php script should be enclosed within <?php and ?>, else
it will not be considered as php code. Adding php code inside the PHP tags is
known as Escaping to php.
•Every expression in PHP ends with a semicolon (;).
•For single line comment, we can either use # or // before the comment line.
•PHP is a case sensitive, which means that a variable $spa is not same as
$SPA.
•PHP uses curly braces to define a code block.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the
variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Rules for PHP variables:
•A variable starts with the $ sign, followed by the name of the variable
•A variable name must start with a letter or the underscore character
•A variable name cannot start with a number
•A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
•Variable names are case-sensitive ($age and $AGE are two different
variables)
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body> Output is : 9
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
</body>
</html> Output is: I love W3Schools.com!
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo “Today is”.date(“Y/m/d”);
echo “Today is”.date(“Y.m.d”);
echo “Today is”.date(“Y-m-d”);
echo “Today is”.date(“l”);
?> Output is : date display in different format.
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$a=12.5;
var_dump($a); //display float(12.5) echo pow(3,5);
echo(pi()); //3.14
echo (sqrt(64)); //8
?>
</body>
</html>
PHP data type:
Data types specifies the type of data and operations that can be
performed on the data. Data types are classified into 2 types:
a. Core data type
b. Special data type

c. Core data type: The core data type include: integer, float, boolean
and string.
• Integer: An integer is a whole number i.e. number without
fractional part (including negative number).
Example:
2454 etc.
Or $a=7005;
• Float: Floating point numbers are represented by float or double
data type.
E.g. 12.56 etc.
Or $a=267.55;
•String: A string is a group of character. They are enclosed between
single or double quotation mark.
Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>
•Boolean: The Boolean data type represent TRUE(1) or FALSE(0) values.
Example:
$x = true;
$y = false;
Note: Here the values true and false are not enclosed within quotes
because these are not strings.
Special data type:

NULL: NULL data type is a special data type which means nothing. If
you create any variable and do not assign any value to it, it will
automatically have NULL stored in it.
Also, we can use NULL value to empty any variable.
Example: $a; or $b=null;

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP constant

<!DOCTYPE html>
<html>
<body>
<?php
define(“demo”,”Welcome to PHP”);
echo demo;
?>
</body> <?php
</html> const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Output: Welcome to PHP
PHP Operators

Operators are used to perform operations on variables and values.


PHP divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
•Logical operators
• String operators
• Arithmetic operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided
by $y
** Exponentiation $x ** $y Result of raising $x to
the $y'th power
• Assignment operators
Assignment Same as... Description

$x =$ y $x =$ y The left operand gets set to the value of


the expression on the right
$x += $y $x = $x +$ y Addition

$x -= $y $x = $x – $y Subtraction

$x *= $y $x = $x *$ y Multiplication

$x /= $y $x = $x / $y Division

$x %=$ y $x = $x %$ y Modulus
• Comparison operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to
$y
!= Not equal $x != $y Returns true if $x is not equal
to $y
<> Not equal $x <> $y Returns true if $x is not equal
to $y
> Greater than $x > $y Returns true if $x is greater
than $y
< Less than $x < $y Returns true if $x is less than
$y
>= Greater than or $x >= $y Returns true if $x is greater
equal to than or equal to $y
<= Less than or equal $x <= $y Returns true if $x is less than
to or equal to $y
• Increment/Decrement operators
Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post- Returns $x, then increments $x by one


increment
--$x Pre- Decrements $x by one, then returns $x
decrement
$x-- Post- Returns $x, then decrements $x by one
decrement
•Logical operators

Operator Name Example Result


and And $x and $y True if both $x and $y are
true
or Or $x or $y True if either $x or $y is
true
xor Xor $x xor $y True if either $x xor $y is
true, but not both
&& And $x && $y True if both $x and $y are
true
|| Or $x || $y True if either $x or $y is
true
! Not !$x True if $x is not true
• String operators

Operator Name Example Result


. Concatenation $txt1 . $txt2 Concatenation of
$txt1 and $txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to
assignment $txt1

<?php
$a="Bhuwan";
$b="Acharya";
$a.=$b;
echo $a;
?>
•Array: An array holds multiple values. There are 3 types of array in PHP, indexed
array, associative array and multi dimensional array.
E.g. index array
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
var_dump($cars);
?> <!DOCTYPE html>
<html>
</body>
<body>
</html> <?php
<?php $cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
$cars=array("volvo",12,12.5); for($x = 0; $x < $arrlength; $x++)
for($i=0;$i<=2;$i++) {
{ echo $cars[$x];
echo $cars[$i]; echo "<br>";
} }
?> ?>
</body>
</html>
E.g. assocative array
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old."; <!DOCTYPE html>
?> <html>
</body> <body>
</html>
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>
E.g. Multidimensional array
<!DOCTYPE html>
<html>
<body>
<?php
$emp = array
(
array(1,"sonoo",400000), 1 Sonoo 400000
array(2,"john",500000),
2 john 500000
array(3,"rahul",300000)
); 3 rahul 300000
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
</body>
</html>
•Object: An object is a collection of both data and function. Objects are created
using the “new” keyword.

// create an object
$obj= new Car(); E.g
<?php
class SayHello
// set property (thisProperty) { function hello()
$obj->thisProperty=“BMW”; {
echo "Hello World";
//Call method or function(getProperty() ) }
$obj->getProperty(); }
$obj=new SayHello;
$obj->hello();
?>

Output: Hello World


•PHP function:

<!DOCTYPE html>
<html>
<head><title>Function</title></head>
<body>
<?php
function sum()
{
$a=5;
$b=2;
$s=$a+$b;
echo “The sum is “.$s;
}
sum(); //function call
</body>
</html>
PHP echo and print Statements
The echo and print are more or less the same. They are both used to
output data to the screen.
The differences are small:
echo has no return value while print has a return value of 1 so it can be
used in expressions.

The PHP echo Statement


The echo statement can be used with or without parentheses: echo or
echo().
Example 1:
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

Example 2:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
echo $x + $y;
?>
The PHP print Statement
The print statement can be used with or without parentheses: print or
print().
Example 1:
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

Example 2:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
print $x + $y;
?>
Super global variables are built-in variables that are always available in all scopes.
<!DOCTYPE html>
<html>
<body>

<?php
$x = 75;
$y = 25;

function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>

</body>
</html>
Q. Write a PHP code to input any two number from user then display its sum.
<!DOCTYPE html>
<html lang="en">
<head> <title>Add two number</title></head>
<body>
<form method="post">
Enter first number:<input type="number" name="num1">
Enter second number:<input type="number" name="num2">
<input type="submit" name="submit" value="Sum">
</form>
<?php
if(isset($_POST['submit'])) or if($_POST)
{
$a=$_POST['num1'];
$b=$_POST['num2'];
$s=$a+$b;
echo "The sum is ".$s;
} ?></body></html>
Q. Write a PHP code to input any two number from user then display its
product.
Q. Write a PHP code to input length and breadth from user then display area of
rectangle.
Q. Write a PHP code to input any number from user then display its factorial.
Q. Write a PHP code to input any number from user then display even or odd.
Q. Write a PHP code to principal amount, rate and time from user then display
simple interest.
Q. Write a PHP code to input any three number from user then display largest
number.
PHP htmlspecialchars() Function
The htmlspecialchars() function converts some predefined characters to
HTML entities.
The predefined characters are:
& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;
<!DOCTYPE html>
<html>
<body>

<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
echo “&#039SPA&#039”;
?>
</body>
</html>
<!DOCTYPE html> *Switch Case
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
Example 1: Example 3:
<?php <!DOCTYPE html>
<html>
for($i;$i<=10;$i++)
<body>
{
echo $i; <?php
} $colors = array("red", "green", "blue", "yellow");
?>
foreach ($colors as $value)
{
Example 2: echo "$value <br>";
<?php }
$i=2; ?>
while($i<=20)
</body>
{ </html>
echo $i;
$i=$i+2; Output: foreach is used only an array case.
} red
green
?> blue
yellow
Example4: Example 5:
<!DOCTYPE html> <?php
<html> $i=2;
<body> do
{
echo $i;
<?php
$i=$i+2;
$age = array("Peter"=>"35", "Ben"=>"37", }while($i<=20);
"Joe"=>"43"); ?>

foreach($age as $x => $val)


{
echo "$x = $val<br>";
}
?>
</body></html> Output:
Peter = 35
Ben = 37
Joe = 43
* Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element
The HTML code of the form looks like this: When the form is submitted, the
form data is sent with method="post".
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The $_SERVER["PHP_SELF"] is a super global variable that
returns the filename of the currently executing script.
HTTP Methods
HTTP works as a request-response protocol between a client
and server.
GET: GET is used to request data from a specified resource.
POST: POST is used to send data to a server to create/update a resource.
PUT: PUT is used to send data to a server to create/update a resource.
HEAD: In other words, if GET /users returns a list of users, then HEAD /users
will make the same request but will not return the list of users.
DELETE: The DELETE method deletes the specified resource.
PATCH: The PATCH method is used to apply partial modifications to a
resource.
OPTIONS: The OPTIONS method describes the communication options for the
target resource.
CONNECT: The CONNECT method is used to start a two-way communications
(a tunnel) with the requested resource.
TRACE: The TRACE method is used to perform a message loop-back test that
tests the path for the target resource (useful for debugging purposes).
GET: GET is used to request data from a specified resource.
Request to server:
GET /first.htm HTTP/1.1
User-Agent: Mozilla/69.0 (compatible; MSIE5.01; Windows 10)
Host: www.javatpoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate <html>
Connection: Keep-Alive <body>
<h1> First Program</h1>
</body>
Response from server: </html>
HTTP/1.1 200 OK
Date: Wed, 4 Dec 2019 5:15:40 GMT
Server: Apache/2.4. 41 (Win32)
Last-Modified: Mon, 2 Dec 2019 15:40:30 GMT
ETag: "34aa387-d-1568eb00"
Vary: Authorization,Accept
Accept-Ranges: bytes
Content-Length: 55
Content-Type: text/html
What is a Regular Expression(RegEx)?
A regular expression can be a single character, or a more complicated
pattern.
Regular expressions can be used to perform all types of text search and
text replace operations.
PHP provides a variety of functions that allow you to use regular
expressions.
The preg_match(), preg_match_all() and preg_replace() functions are
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>

</body>
</html> Output: 1
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<?php <?php
$str = "The rain in SPAIN falls mainly $str = "Visit Microsoft!";
on the plains."; $pattern = "/microsoft/i";
$pattern = "/ain/i"; echo preg_replace($pattern,
echo preg_match_all($pattern, $str); "W3Schools", $str);
?> ?>

</body> </body>
</html> Output: 4 </html>

Output:
Visit W3Schools!
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
* MySQLi extension (the "i" stands for improved)
* PDO (PHP Data Objects)

In this, and in the following chapters we demonstrate three ways of


working with PHP and MySQL:
1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO(PHP Data Objects)
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed
in most cases, when php5 mysql package is installed.
For installation details, go to:
http://php.net/manual/en/mysqli.installation.php

The die() is an inbuilt function in PHP. It is used to print message and exit
from the current php script.
Open a Connection to MySQL
Example 1: MySQLi (object-oriented)
Before we can access data in the MySQL database, we need to be able
to connect to the server:
<?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";
?>
Example2 (MySQLi Procedural) mysqli_connect() function opens a new
<?php connection to the MySQL server.
$servername = "localhost";
$username = "username“;
$password = "password";

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

// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
else PHP mysqli_connect_error() function returns
{ an string value representing the description of
echo "Connected successfully"; the error from the last connection call, incase
of a failure. If the connection was successful
} ?> this function returns Null.
Example 3 (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";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?> An exception is an object that describes an error or unexpected
behaviour of a PHP script.
Close the Connection

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


close the connection before, use the following:
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;

PHP Create a MySQL Database


A database consists of one or more tables.
You will need special CREATE rights to create or to delete
a MySQL database.
The following examples create a database named "myDB":
<?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);
}

// Create database
$sql = "CREATE DATABASE myDB"; === It is used to check the equality of both
if ($conn->query($sql) === TRUE) { operands and their data type.
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close(); The query() / mysqli_query() function performs a query
?> against a database.
END of Unit

Best Wishes for Your Final Exam

You might also like