You are on page 1of 20

Java-script fundamentals and PHP scripting

Server-side scripting Vs Client-side Scripting


A server-side script is processed on the web server when the user requests information. These kinds of scripts can run before
a web page is loaded. They are needed for anything that requires dynamic data, such as storing user login details. Server-
side scripting is a method of designing websites so that the process or user request is run on the originating server. Server-
side scripts provide an interface to the user and are used to limit access to proprietary data and help keep control of the
script source code. It is based on the use of scripts that are carried out by the web server using the appropriate scripting
languages when a client requests the corresponding content. The languages that can be used to create server-side scripts
include: ASP, C, JAVA, JavaScript, PHP, Ruby, Python etc.
A client-side script is a program that is processed within the client browser. These kinds of scripts are small programs which
are downloaded, compiled and run by the browser. JavaScript is an important client-side scripting language and widely used
in dynamic websites. The script can be embedded within the HTML or stored in an external file. A client side script is a
program that is processed within the client browser. Some of the languages include: JavaScript, HTML, CSS, VB script etc.
What is JavaScript
JavaScript is a programming language that executes on the browser. It turns static HTML web pages into interactive web
pages by dynamically updating content, validating form data, controlling multimedia, animate images, and almost
everything else on the web pages. JavaScript is a text-based programming language used both on the client-side and server-
side that allows you to make web pages interactive.
JavaScript is mainly used for web-based applications and web browsers. JavaScript is the third most important web
technology after HTML and CSS. JavaScript can be used to create web and mobile applications, build web servers, create
games, etc.

JavaScript advantages
 Fast speed: JavaScript is executed on the client side that’s why it is very fast.
 Easy to learn: JavaScript is easy to learn. Any one which have basic knowledge of programming can easily learn
JavaScript.
 Versatility: It refers to lots of skills. It can be used in a wide range of applications.
 Browser Compatible: JavaScript supports all modern browsers. It can execute on any browser and produce same result.
 Server Load: JavaScript reduce the server load as it executes on the client side.
 Rich interfaces: JavaScript provides the drag and drop functionalities which can provides the rich look to the web pages.
 Popularity: JavaScript is a very popular web language because it is used every where on the web.
 Regular Updates: JavaScript updated annually by ECMA.

JavaScript disadvantages
 Code Visibility: JavaScript code is visible to every one and this is the biggest disadvantage of JavaScript.
 Stop Render: One error in JavaScript code can stop whole website to render.
 No Multiple Inheritance: JavaScript only support single inheritance.

1
Comparison between server-side and client-side scripting

BASIS OF SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING


COMPARISON
Use It is used at the backend where the source It is used at the front end which users can see
code is not viewable or hidden at the from the browser.
client side (browser).
Script A web server runs the script for server- A browser runs the script for client-side
Running side scripting that creates the page which scripting that is already present in the user’s
needs to be sent to the browser. computer.

Occurrence It happens when a user’s browser initiates It happens when the browser possesses all the
a server request. Dynamic pages are then codes and the page in later changed according
created based on several conditions. to the user’s input.

Execution The scripting process for the server side is The scripting process of client server is
done on remote computer and hence the executed on a local computer and thus the
response is comparatively slower than the response is comparatively quicker when
client side one. compared to server side scripting.

Operation A server can carry out a server-side script, A browser can perform the client-side scripting
but cannot perform the client side after receiving the page sent by the server.
scripting.

Connection It helps in connecting to the databases It does not connect to the databases that are
to the that are already present in the web on the web server.
database server.
Suitability It is excellent for any area that requires It is excellent for any case which requires user
loading of dynamic data. interaction.

Languages Languages used in server scripting are Languages commonly used


Ruby on Rails, PHP, ColdFusion, Python, for client-side scripting are Javascript, HTML,
ASP, Perl, etc. CSS, VB script etc.

Access To It has access to all the files present in the It has no access to all the files present in the
Files web server. web server.
Security It is more secure than client side scripting It is less secure because the scripts are usually
as the server side scripts are usually not hidden from the client end.
hidden from the client end.

Adding JavaScript to HTML Pages


There are following three ways in which users can add JavaScript to HTML pages.
1. Embedding code
2. Inline code
3. External file
1. Embedding code:-
To add the JavaScript code into the HTML pages, we can use the <script>.....</script> tag of the HTML that wrap around
JavaScript code inside the HTML program. Users can also define JavaScript code in the <body> tag (or we can say body
section) or <head> tag because it completely depends on the structure of the web page that the users use.

2
We can understand this more clearly with the help of an example, how to add JavaScript to html Example:
<html>
<head>
<title> page title</title>
<script>
document.write(“Welcome to our first page”);
</script>
</head>
<body>
<p>Here we saw how to add JavaScript in the head section </p>
</body> </html>

Output:

We can also define the JavaScript code in the <body> tags or body section like this:
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
</head>
<body> <script>
document.write(“Welcome to our first page”);
</script>
<p>In this example we saw how to add JavaScript in the body section </p>
</body>
</html>
Output

3
2. Inline code:-
Generally, this method is used when we have to call a function in the HTML event attributes. There are many cases (or
events) in which we have to add JavaScript code directly eg.,onmouseover event, onclick, etc.
Let’s see with the help of an example, how we can add JavaScript directly in the html without using the <script>.... </script>
tag.
Let’s look at the example.
<!DOCTYPE html >
<html> <head><title> page title</title>
</head>
<body>
<p>
<a href= ‘‘#” onclick= “alert(‘Welcome !’);”>Click Me</a>
</p>
<p> in this example we saw how to use inline JavaScript or directly in an HTML tag. </p> </body>
</html>
Output

3. External file:-
We can also create a separate file to hold the code of JavaScript with the (.js) extension and later incorporate/include it into
our HTML document using the src attribute of the <script> tag. It becomes 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.
In this example, we will see how we can include an external JavaScript file in an HTML document. Let’s understand through
a simple example.
<html> <head>
<meta charset= “utf-8”>
<title>Including a External JavaScript File</title>
</head> <body><form>
<input type= “button” value=”Result” onclick= “display()”/>
</form>
<script src= “hello.js”>
</script> </body> </html>
Now let’s create separate JavaScript file Hello.js in the same folder:
function display() {
alert(“Hello World!”);
}
Both of the above programs are saved in the same folder, but you can also store JavaScript code in a separate folder, all just
you need to provide the address/path of the (.js) file in the src attribute of <script> tag.
Output is:

4
Advantages of External JavaScript
There will be following benefits if a user creates an external JavaScript:
 It helps in the reusability of code in more than one HTML file.
 It allows easy code readability.
 It is time-efficient as web browsers cache the external js files, which further reduces the page loading time.
 It enables both web designers and coders to work with html and js files parallelly and separately, i.e., without facing
any code conflictions.
 The length of the code reduces as only we need to specify the location of the js file.
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add information about the code, warnings or
suggestions so that end user can easily interpret the code. The JavaScript comment is ignored by the JavaScript engine i.e.
embedded in the browser.
Types of JavaScript Comments
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the statement. Let’s see the example of
single-line comment i.e. added before the statement.
<script>
// It is single line comment document.write(“hello javascript”);
</script>

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
/* your code here */
It can be used before, after and middle of the statement. <script>
/* It is multi line comment. It will not be displayed */
document.write(“example of javascript multiline comment”); </script>

Data types in JavaScript.


1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don’t need to specify type of the variable because it is dynamically used
by JavaScript engine. You need to use var keyword here to specify the variable. It can hold any type of values such as numbers,
strings etc. For example:
There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description

String represents sequence of characters e.g. “hello”


Number represents numeric values e.g. 10
Boolean represents Boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

5
JavaScript non-primitive data types

The non-primitive data types are as follows:


Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

Variables and operators


JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript: local variable and
global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore (_ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Valid JavaScript variables


var x = 10;
var _value= “ncc”;

Invalid java Script variables


var 123=10; var *aa=20;

JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:
<script> function abc(){
var x=15;//local variable
}
</script>
Or,
<script> If(15<16){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with
window object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.write(data);
}
function b(){
document.write(data);
}
a();//calling JavaScript function
b();
</script>

6
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example: var sum=15+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


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

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators are as follows:
Operator Description Example
== Is equal to 10==20 = false
!= Not equal to 10!=20 = true
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

7
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10 + 10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


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

Functions and control structure if-else, if-elseif, switch-case, for, while, do while loop
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of if
statement in JavaScript.
1. If Statement
2. If else statement
3. If else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
Let’s see the simple example of if statement in JavaScript.
<script> var a=20; if(a>10){
document.write(“value of a is greater than 10”);
}
</script>

JavaScript If...else Statement


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

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

8
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
<script> var a=40; if(a%2==0){
document.write(“a is even number”);
} else{
document.write(“a is odd number”);
} </script>

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The syntax of JavaScript if else if statement is
given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
} else{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<script> var a=20;
if(a==10)
{
document.write(“a is equal to 10”);
}
else if(a==15)
{
document.write(“a is equal to 15”);
}
else if(a==20)
{
document.write(“a is equal to 20”);
}
else
{
document.write(“a is not equal to 10, 15 or 20”);
} </script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement. But it
is convenient than if..else..if because it can be used with numbers, characters etc.
The syntax of JavaScript switch statement is given below.
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched; }
9
Let’s see the simple example of switch statement in JavaScript. ( Here, the value 1 to 7 is entered into a textbox and passed it
to the variable named ‘p’)
<html>
<head>
<title>switch_case</title>
<script type="text/javascript">
function calculate(){
var p=document.getElementById("number").value;
if(p==' '){
alert("Enter the number at first");
document.getElementById("number").focus();
}
else
{
switch(p)
{
case '1':
alert("Sunday");
break;
case '2':
alert("Monday");
break;

case '3':
alert("Tuesday");
break;
case '4':
alert("Wednesday");
break;
case '5':
alert("Thursday");
break;
case '6':
alert("Friday");
break;
case '7':
alert("Saturday");
break;
default:
alert("wrong number");
}
document.getElementById("number").focus();
}
}
</script>
</head>
<body>
<form>
Enter a number from 1 to 7 in the box below:
<input type="text" id="number"><br>
<input type="button" value="print" onclick="calculate()">
</form>
</body>
</html>
10
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.
The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=3; i++)
{
document.write(i + “<br/>”) ;
}
</script>
Output:
1
2
3
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is
not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script> var i=10;
while (i<=15)
{
document.write(i + “<br/>”);
i++;
}
</script>
Output:
10
11
12
13
14
15
JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at
least once whether condition is true or false. The syntax of do while loop is given below.
do {
code to be executed
} while (condition);
Let’s see the simple example of do while loop in javascript.
11
<script>
var i=21;
do {
document.write(i + “<br/>”);
i++;
}while (i<=23);
</script>
Output:
21
22
23

Common HTML Events

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading body of the page

Object based programming with Java Script and Event handling


JavaScript Objects
A JavaScript object is an entity having state and behavior (properties and method). Objects are the real things of the world.
For example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-based language.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN} As you can see, property and
value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:100,name:” Kumar”, salary:400}
document.write(emp.id+” “+emp.name+” “+emp.salary);
</script>
Output of the above example 100 Kumar 400

By creating instance of Object


The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script> var emp=new Object(); emp.id=100; emp.name= “ncc”; emp.salary=2000;
document.write(emp.id+” “+emp.name+” “+emp.salary);
</script>
Output of the above example 100 ncc 2000

12
By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this
keyword.
The ‘this’ keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary; }
e=new emp(103, “Anil koirala”,30000);
document.write(e.id+” “+e.name+” “+e.salary);
</script>
Output of the above example
103 Anil koirala 30000

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to add property in the function with same
name as method.
The example of defining method in object is given below.
<script>
function emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary; function changeSalary(otherSalary){
this.salary=otherSalary;
} }
e=new emp(113,” “Sonu”,3000); document.write(e.id+” “+e.name+” “+e.salary);
e.changeSalary(4500);
document.write(“<br>”+e.id+” “+e.name+” “+e.salary);
</script>
Output of the above example
113 Sonu 3000
113 Sonu Jaiswal 4500

JavaScript Form Validation


It is important to validate the form submitted by the user because it can have inappropriate values. So, validation is must
to authenticate user. JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

13
The following form uses JavaScript codes to validate the given form.
<html> <head><title> SignUp Page</title>
</head>
<body align= "center" >
<h2> CREATE YOUR ACCOUNT</h2>
<table cellspacing= "2" align= "center" cellpadding= "4" border= "0">
<tr><td> Name</td>
<td><input type= "text" placeholder= "Enter your name" id= "n1"></td></tr>
<tr><td>Email </td>
<td><input type= "text" placeholder="Enter your email id" id= "e1"></td></tr>
<tr><td> Set Password</td>
<td><input type="password" placeholder= "Set a password" id= "p1"></td></tr>
<tr><td>Confirm Password</td>
<td><input type="password" placeholder="Confirm your password" id="p2"></td></tr>
<tr><td>
<input type="submit" value="Create" onClick="create_account()"/>
</table>
<script type= "text/javascript">
function create_account(){
var n=document.getElementById("n1").value;
var e=document.getElementById("e1").value;
var p=document.getElementById("p1").value;
var cp=document.getElementById("p2").value;
//Code for password validation
var letters = /^[A-Za-z]+$/;
var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//other validations required code
if(n==''||e==''||p==''||cp==''){
alert("Enter each details correctly");
}
else if(!letters.test(n))
{
alert("Name is incorrect must contain alphabets only");
}
else if (!email_val.test(e))
{
alert("Invalid email format please enter valid email id");
}
else if(p!=cp)
{
alert("Passwords not matching");
}
else if(document.getElementById("p1").value.length > 12)
{
alert("Password maximum length is 12");
}
else if(document.getElementById("p1").value.length < 6)
{
alert("Password minimum length is 6");
}
else{
alert("Your account has been created successfully... Redirecting to youtube.com");
window.location="https://youtube.com/";
} } </script> </body></html>
14
PHP
Server Side Scripting using PHP
PHP is a server side scripting language used to create dynamic web pages. PHP stands for Hypertext Preprocessor. It is an
interpreted language. It is embedded in HTML. It is an open source language. PHP supports different databases hence large
scale websites are developed using PHP.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some important features of PHP given
below:
Performance: PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP.
PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster
processing speed and better performance.
Open Source: PHP source code and software are freely available on the web. You can develop all the versions of PHP
according to your requirement without paying any cost. All its components are free to download and use.
Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding with it
Embedded: PHP code can be easily embedded within HTML tags and script.
Platform Independent: PHP is available for WINDOWS, MAC, LINUX& UNIX operating system. A PHP application developed in
one OS can be easily executed in other OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g.,
E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.
Web servers Support: PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc
Security: PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and
malicious attacks.
Control: Different programming languages require long script or code, whereas PHP can do the same work in a few lines of
code. It has maximum control over the websites like you can make changes easily whenever you want.
A Helpful PHP Community:It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.
Basic PHP syntax
A PHP script can be placed anywhere in the document. A PHP script starts with
• The default file extension for PHP files is “.php”
• A PHP file normally contains HTML tags, and some PHP scripting code
• PHP statements are terminated by semicolon (;)
• In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are not case-sensitive
A PHP script starts with <?php and ends with ?>:
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 First PHP” on a web page:
<!DOCTYPE> <html> <body> <?php
echo “<h2>Hello First PHP</h2>”;
?> </body> </html>
PHP Data types
PHP data types are used to hold different types of data or
values. PHP supports 8 primitive data types that can be
categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types

15
PHP Data Types: Scalar Types decimal point, including a negative or positive sign.
It holds only single value. There are 4 scalar data types in Example:
PHP. <?php
1. Boolean $n1 = 19.34;
2. integer $n2 = 54.472;
3. float $sum = $n1 + $n2;
4. string echo “Addition of floating numbers:” .$sum;
PHP Data Types: Compound Types ?>
It can hold multiple values. There are 2 compound data Output:
types in PHP. Addition of floating numbers: 73.812
1. array
2. object PHP String
PHP Data Types: Special Types A string is a non-numeric data type. It holds letters or any
There are 2 special data types in PHP. alphabets, numbers, and even special characters.
1. resource String values must be enclosed either within single quotes
2. NULL or in double quotes. But both are treated differently. To
clarify this, see the example below: Example:
PHP Boolean <?php
Booleans are the simplest data type works like switch. It $company = “Java”;
holds only two values: TRUE (1) or FALSE (0). It is often //both single and double quote statements will treat
used with conditional statements. If the condition is different
correct, it returns TRUE otherwise FALSE. Example: echo “Hello $company”;
<?php echo “</br>”;
if (TRUE) echo “This condition is TRUE.”; if (FALSE) echo ‘Hello $company’;
echo “This condition is FALSE.”; ?>
?> Output: Output:
This condition is TRUE. Hello Java
Hello $company
PHP Integer PHP Array
Integer means numeric data with a negative or positive An array is a compound data type. It can store multiple
sign. It holds only whole numbers, i.e., numbers without values of same data type in a single variable. Example:
fractional part or decimal points. <?php
Rules for integer: $bikes = array (“Royal Enfield”, “Yamaha”, “KTM”);
 An integer can be either positive or negative. var_dump($bikes); //the var_dump() function returns the
 An integer must not contain decimal point. datatype and values
 Integer can be decimal (base 10), octal (base 8), or echo “</br>”;
hexadecimal (base 16). echo “Array Element1: $bikes[0] </br>”;
 The range of an integer must be lie between echo “Array Element2: $bikes[1] </br>”; echo “Array
2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31. Element3: $bikes[2] </br>”;
Example: ?>
<?php Output:
$dec1 = 34; array(3) { [0]=> string(13) “Royal Enfield” [1]=> string(6)
$oct1 = 0243; “Yamaha” [2]=> string(3) “KTM” } Array Element1: Royal
$hexa1 = 0x45; Enfield
echo “Decimal number:” .$dec1. “</br>”; echo “Octal Array Element2: Yamaha
number:” .$oct1. “</br>”; echo “HexaDecimal number:” Array Element3: KTM
.$hexa1. “</br>”; ?>

PHP Float
A floating-point number is a number with a decimal point.
Unlike integer, it can hold numbers with a fractional or

16
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.
Output:
Bike Model: Royal Enfield
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external
PHP resources. For example - a database call. It is an external resource. This is an advanced topic of PHP, so we will discuss it
later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case
sensitive.
The special type of data type NULL defined a variable with no value. Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Operators (Arithmetic, logical, comparison, operator precedence)
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to perform
operations on variables or values. For example:

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc. with
numeric values.

Operator Name Example Explanation


+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b
The exponentiation (**) operator has been introduced in PHP 5.6.

Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison operators are
given:

Operator Name Example Explanation


== Equal $a == $b Return TRUE if $a is equal to $b
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal to $a >= $b Return TRUE if $a is greater than or equal $b
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b

17
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation and
manipulation of specific bits within the integer.

Operator Name Example Explanation


and And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
&& And $a && $b Return TRUE if either $a and $b are true
|| Or $a || $b Return TRUE if either $a or $b is true
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about
variables:

 As PHP is a loosely typed language, so we do not need to declare the data types of the variables.
It automatically analyzes the values and makes conversions to its correct datatype.

 After declaring a variable, it can be reused throughout the code.


 Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:


$variablename=value;

Rules for declaring PHP variable:

 A variable must start with a dollar ($) sign, followed by the variable name.
 It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
 A variable name must start with a letter or underscore (_) character.
 A PHP variable name cannot contain spaces.
 One thing to be kept in mind that the variable name cannot start with a number or special symbols.
 PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

PHP Variable: Declaring string, integer, and float


Let’s see the example to store string, integer, and float values in PHP variables. File: variable1.php
<?php
$str= “hello string”;
$x=200; $y=44.6;
echo “string is: $str <br/>”; echo “integer is: $x <br/>”; echo “float is: $y <br/>”; ?>
Output:
string is: hello string integer is: 200 float is: 44.6
Write a Program to display count, from 1 to 5 using
PHP loop as given below.
<?php
$count = 1;
while($count <= 5){
echo $count; echo “<br>” ;
$count++; }
?>

18
return ($number * factorial($number-1));
}}
Write a program to print 2 php variables using single echo factorial(4);
echo statement. ?>
<?php
Write a program to print “Hello World” using echo only?
$message_1 = “Good Morning.”; <?php
$message_2 = “Have a nice day!”; echo “Hello World”; ?>
echo $message_1.” “. $message_2; ?>
Write a program to print “Welcome to the PHP World”
Write a program to show days of the week . using some part of the text in variable & some part
<?php directly in echo.
<?php
$day = “7”;
$message = “Welcome to the PHP World”;
switch ($day) {
echo $message; ?>
case “1”:
echo “It is Monday!”; Write a program to check student grade based on the
break; marks using if-else statement.
case “2”: Conditions:
echo “It is today!”; If marks are 60% or more, grade will be First Division.
break; If marks between 45% to 59%, grade will be 2nd division.
case “3”: If marks between 33% to 44%, grade will be Third Division.
echo “It is Wednesday!”; If marks are less than 33%, student will be Fail.
break; <?php
case “4”: $marks = 80;
echo “It is Thursday!”; if ($marks>=60)
break; { $grade = “First Division”;}
case “5”: else if($marks>=45){
echo “It is Friday!”; $grade = “Second Division”;}
break; else if($marks>=33){
case “6”: $grade = “Third Division”;}
echo “It is Saturday!”; else{
break; case “7”: $grade = “Fail”; }
echo “It is Sunday!”; echo “Student grade: $grade”; ?>
break; Output
default: Student grade: First Division
echo “Invalid number!”;
Write a program to calculate factorial of a number using
}
for loop in php.
?>
<?php
$num = 4; $factorial = 1;
Write a PHP program to find factorial of a number using
for ($x=$num; $x>=1; $x--){
recursive function.
$factorial = $factorial * $x;}
<?php
echo “The factorial of $num is $factorial”;?>
function factorial($number) {
if ($number < 2) { Output
return 1; } The factorial of 4 is 24
else {

19
SQL
Structured Query Language SQL is the acronym for Structured Query Language. SQL is the standard language for
communicating with relational database management systems. SQL is used to query, insert, update and modify data.
Some common relational database management systems that use SQL are: Oracle, Sybase, MS SQL Server, MS Access,
MySQL, etc. SQL Command SQL defines following ways to manipulate data stored in an RDBMS.

DDL: Data Definition Language Data Definition Language includes changes to the structure of the table like creation of
table, altering table, deleting a table etc. All DDL commands are auto-committed. That means it saves all the changes
permanently in the database.

Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table

DML: Data Manipulation Language DML commands are used for manipulating the data stored in the table and not the
table itself. DML commands are not auto-committed. It means changes are not permanent to database, they can be
rolled back.

Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables

DCL: Data Control Language Data control language are the commands to grant and take back authority from any
database user.

Command Description

grant grant permission of right

revoke take back permission.

20

You might also like