0% found this document useful (0 votes)
15 views

Server Side Scripting

The document discusses server-side scripting and PHP. It covers topics like what server-side scripting is, how PHP works as a server-side language, PHP syntax, variables, data types, operators, and comments. It provides details on features and uses of PHP.

Uploaded by

Kalay Ro Son
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Server Side Scripting

The document discusses server-side scripting and PHP. It covers topics like what server-side scripting is, how PHP works as a server-side language, PHP syntax, variables, data types, operators, and comments. It provides details on features and uses of PHP.

Uploaded by

Kalay Ro Son
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Server Side Scripting

 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 limit access to
proprietary data and help keep control of the script source code.
 PHP is a server side script that is interpreted on the server while JavaScript is
an example of a client side script that is interpreted by the client browser.
 Both PHP and JavaScript can be embedded into HTML pages.
 Following are the examples of Sever Side Scripting:- Java, JavaScript(using
SSJS(Server-Side JS) e.g. Node JS,PHP etc.

PHP (Hypertext Pre-processor)


 PHP is a server side scripting language that is also an interpreted language.
 It is basically used for developing software applications that have dynamic
content and require constant interactions with databases.
 It is an open source language making it one of the most sought out platforms
for developers and companies.
 PHP stands for Hypertext Pre-processor.
 PHP scripts can only be interpreted on a server that has PHP installed.
 PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in
1995.
 The client computers accessing the PHP scripts require a web browser only.
 A PHP file contains PHP tags and ends with the extension ".php".
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use.
Features of PHP:
 PHP is an interpreted language, i.e., there is no need for compilation.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is a server-side scripting language, which is used to manage the dynamic
content of the website.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

Object oriented programming with server side scripting


 Object Oriented is an approach to software development that models
application around real world objects such as employees, cars, bank
accounts, etc.
 A class defines the properties and methods of a real world object. An
object is an occurrence of a class.
The three basic components of object orientation are;
 Object oriented analysis – functionality of the system
 Object oriented designing – architecture of the system
 Object oriented programming – implementation of the application
 PHP is an object oriented scripting language; it supports all of the above
principles.
The above principles are achieved via;
 Encapsulation - via the use of “get” and “set” methods 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.
 All PHP code goes between the php tag.
 It starts with <?php and ends with ?>.
 PHP script can be placed anywhere in the document.
 A PHP script starts with <?php and ends with ?>:
Syntax:
<?php
// PHP code goes here
?>
Basic Example of php:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

PHP Variables
Variables are "containers" for storing information.
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)
PHP data type
PHP has a total of eight data types which we use to construct our variables −
 Integers − are whole numbers, without a decimal point, like 4195.
 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to
PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound
- the compound types can package up other arbitrary values of arbitrary type,
whereas the simple types cannot.

PHP echo and print Statements


 echo and print : Both echo and print are used to display result(Statements).
 The echo and print statement can be used with or without parentheses.
Difference between echo and print
 echo - can output one or more strings
 print - can only output one string, and returns always 1 echo is faster than
print as echo does not return any value.

PHP Comments
 A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at the
code.
Comments can be used to:
 Let others understand your code
 Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-
figure out what they did. Comments can remind you of what you were
thinking when you wrote the code
PHP supports several ways of commenting:
Syntax for single-line comments:
<?php
// This is a single-line comment

# This is also a single-line comment


?>
Syntax for multi-line comments:
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
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
 Array operators
 Conditional assignment operators

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

Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is


assigned to the left operand.

+= Add then $a += $b Addition same as $a = $a + $b


Assign

-= Subtract then $a -= $b Subtraction same as $a = $a -


Assign $b

*= Multiply then $a *= $b Multiplication same as $a = $a


Assign * $b

/= Divide then $a /= $b Find quotient same as $a = $a /


Assign $b
(quotient)

%= Divide then $a %= $b Find remainder same as $a =


Assign $a % $b
(remainder)

Bitwise Operators
The bitwise 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 $a & $b Bits that are 1 in both $a and


$b are set to 1, otherwise 0.
| Or (Inclusive $a | $b Bits that are 1 in either $a or
or) $b are set to 1

^ Xor $a ^ $b Bits that are 1 in either $a or


(Exclusive $b are set to 0.
or)

~ Not ~$a Bits that are 1 set to 0 and bits


that are 0 are set to 1

<< Shift left $a << $b Left shift the bits of operand


$a $b steps

>> Shift right $a >> $b Right shift the bits of $a


operand by $b number of
places

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

=== Identical $a === Return TRUE if $a is equal to $b,


$b and they are of same data type

!== Not identical $a !== $b Return TRUE if $a is not equal to


$b, and they are not of same data
type
!= 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 $a <= $b Return TRUE if $a is less than or


equal to equal $b

>= Greater than or $a >= $b Return TRUE if $a is greater than


equal to 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

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value
of a variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one,


then return $a

$a++ Return $a, then increment the value


of $a by one
-- decrement --$a Decrement the value of $a by one,
then return $a

$a-- Return $a, then decrement the value


of $a by one

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 && Return TRUE if either $a and $b are


$b true

|| Or $a || $b Return TRUE if either $a or $b is true

String Operators
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and


$b

.= Concatenation $a .= $b First concatenate $a and


and Assignment $b, then assign the
concatenated string to $a,
e.g. $a = $a . $b

Variables Scopes
 The scope of a variable is defined as its range in the program under which it
can be accessed.
 In other words, "The scope of a variable is the portion of the program within
which it is defined and can be accessed."
PHP has three types of variable scopes:
 Local variable
 Global variable
 Static variable

Local variable
 The variables that are declared within a function are called local variables for
that function.
 These local variables have their scope only in that particular function in which
they are declared.
 This means that these variables cannot be accessed outside the function, as
they have local scope.
 A variable declaration outside the function with the same name is completely
different from the variable declared inside the function.
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Global variable
 The global variables are the variables that are declared outside the
function. These variables can be accessed anywhere in the program.
 To access the global variable within a function, use the GLOBAL
keyword before the variable
 . However, these variables can be directly accessed or used outside the
function without any keyword.
 Therefore there is no need to use any keyword to access a global
variable outside the function.
Example:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Static variable
 It is a feature of PHP to delete the variable, once it completes its
execution and memory is freed.
 Sometimes we need to store a variable even after completion of
function execution.
 Therefore, another important feature of variable scoping is static
variable.
 We use the static keyword before the variable to define a variable,
and this variable is called as static variable.
Example:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

//first function call


static_var();

//second function call


static_var();
?>
Database Connectivity
 A database connection is a facility in computer science that allows client
software to talk to database server software, whether on the same machine or
not.
 A connection is required to send commands and receive answers, usually in
the form of a result set.
 Connections are a key concept in data-centric programming

Connection PHP database


 The collection of related data is called a database.
 XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is
among the simple light-weight local servers for website development.
 Before making a connection, we should have details like- hostname, data base
user name, db password , port.
 Every programming language has its own unique way of making a connection
with the database.
 It is a very simple couple of lines of code to connect with db
 In the php language, we can make connections in three methods: mysql, mysqli
extension and PDO. But we will do using mysql.
In the PHP language we can make database connection in a below-
mentioned way:
• First of all you must be install any XAMPP or WAMP or MAMP kind of
software in your laptop or computer. By these software you will be get local
web server Apache, PHP language and MySQL database.
• After installation of any of these laptop or desktop software you need to
check your localhost is working or not. Open your browser and check this URL
http://127.0.0.1 or http://localhost/ . If this is working it means you have the
local web server activated with PHP/MySQL.
• If you have the above installation you can go ahead to start your PHP
coding
Requirements: XAMPP web server procedure:
 Start XAMPP server by starting Apache and MySQL.
 Write PHP script for connecting to XAMPP.
 Run it in the local browser.
 Database is successfully created which is based on the PHP code.
Steps in details:
PHP code for creating connection and creating database
<?php
// Server name must be localhost
$servername = "localhost";
// In my case, user name will be root
$username = "root";
// Password is empty
$password = "";
// Creating a connection
$conn = new mysqli($servername,
$username, $password)
// Check connection
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
// Creating a database named test
$sql = "CREATE DATABASE test";
if ($conn->query($sql) === TRUE) {
echo "Database with name test";
} else {
echo "Error: " . $conn->error;
}
// Closing connection
$conn->close();
?>
Save the file as “data.php” in htdocs folder under XAMPP folder.
Then open your web browser and type localhost/data.php
Creating table using php
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,"test");
$sql = "Create table tbl1(id int not null primary key Auto_increment, first_name
varchar(10) not null, last_name varchar(10) not null, email varchar(30) not null
unique)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Inserting Data to table
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,"test");
$sql = "INSERT INTO tbl1(first_name, last_name, email)
VALUES ('ram', 'thapa', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Fetching data from the database
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
//selectin database
mysqli_select_db($conn,"test");
//checking database
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT first_name, last_name, email from ram";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// OUTPUT DATA OF EACH ROW
while($row = $result->fetch_assoc())
{
echo "First Name: " .
$row["first_name"]. " - Last Name: " .
$row["last_name"]. " | Email: " .
$row["email"]."<br>";
}
}
$conn->close();
?>
SQL
 SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
 SQL is the standard language for Relational Database System.
 All the Relational Database Management Systems (RDMS) like MySQL, MS
Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their
standard database language
SQL Commands
 SQL commands are instructions.
 It is used to communicate with the database. It is also used to perform specific
tasks, functions, and queries of data.
 SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
Data Definition Language (DDL)
 DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
 All the command of DDL are auto-committed that means it permanently save
all the changes in the database.
CREATE Command
CREATE is a DDL command used to create databases, tables, triggers and other
database objects.
Syntax:
CREATE Database Database_Name;
Example:
Create Database Books;
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email
VARCHAR2(100), DOB DATE);

DROP Command
DROP is a DDL command used to delete/remove the database objects from the
SQL database.
Syntax:
DROP DATABASE Database_Name;
Example:
DROP DATABASE Books;
Syntax:
DROP TABLE Table_Name;
Example:
DROP TABLE Student;
ALTER Command
ALTER is a DDL command which changes or modifies the existing structure of
the database, and it also changes the schema of database objects.
Syntax to add a newfield in the table:
ALTER TABLE name_of_table ADD column_name column_definition;
ALTER TABLE table_name MODIFY(column_definitions....);
Example:
ALTER TABLE Student ADD Father's_Name Varchar(60);
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

TRUNCATE Command
TRUNCATE is another DDL command which deletes or removes all the records
from the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;

Data Manipulation Language


 DML commands are used to modify the database. It is responsible for all form
of changes in the database.
 The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollback.
SELECT
The SELECT command shows the records of the specified table. It also shows
the particular record of a particular column by using the WHERE clause
Syntax:
SELECT column_Name_1, column_Name_2, ….., column_Name_N FROM
Name_of_table;
If we want to retrieve the data from all the columns of the table, we have to use
the following SELECT command:
SELECT * FROM table_name;
Example:
SELECT * FROM Student;
SELECT Emp_Id, Emp_Salary FROM Employee;

INSERT
INSERT is another most important data manipulation command in Structured
Query Language, which allows users to insert data in database tables.
Syntax:
INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 ,
column_Name3 , .... column_NameN )
Example:
INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES
(104, Anmol, 89, 19);

UPDATE
UPDATE is another most important data manipulation command in Structured
Query Language, which allows users to update or modify the existing data in
database tables.
Syntax:
UPDATE Table_name SET [column_name1= value_1, ….., column_nameN =
value_N] WHERE CONDITION;
Example:
UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;

DELETE
DELETE is a DML command which allows SQL users to remove single or
multiple existing records from the database tables.
This command of Data Manipulation Language does not delete the stored data
permanently from the database. We use the WHERE clause with the DELETE
command to select specific rows from the table.
Syntax:
DELETE FROM Table_Name WHERE condition;
Example:
DELETE FROM Product WHERE Product_Id = 'P202' ;
DELETE FROM Student WHERE Stu_Marks > 70 ;

Data Control Language


DCL commands are used to grant and take back authority from any database
user.
a. Grant:
It is used to give user access privileges to a database.
Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER,
ANOTHER_USER;

b. Revoke:
It is used to take back permissions from the user.
Example
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

Transaction Control Language


 TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
 These operations are automatically committed in the database that's why
they cannot be used while creating tables or dropping them.
Commit:
Commit command is used to save all the transactions to the database.
Syntax:
COMMIT;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
Rollback:
Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
SAVEPOINT:
It is used to roll the transaction back to a certain point without rolling back the
entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Example:
SAVEPOINT Insertion;

You might also like