Final Unit 3 2079 Chaitra Full Modified
Final Unit 3 2079 Chaitra Full Modified
<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.
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 id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<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 "));
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
<h2>JavaScript Objects</h2>
<p>Creating an object:</p>
<p id="demo"></p>
<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
</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;
}
};
<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:
Form events:
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>
</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.
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
//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
• 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 = $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
<?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");
</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();
?>
<!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.
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 &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >
<!DOCTYPE html>
<html>
<body>
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
echo “'SPA'”;
?>
</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"); ?>
</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)
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
// 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