Unit 2 Server Side Scripting With DB Connection
Unit 2 Server Side Scripting With DB Connection
Database Connectivity
NOTE:
• A scripting language is a language that interprets scripts at runtime.
• Scripts are usually embedded into other software environments.
By: Laxman Kharel
Server side Technology are a set of tools and programming languages that are used
to design, build and maintain server side operation of a web application.
Server-side scripts are discrete blocks of program code that execute on a web server
(as opposed to a web client) computer.
Server-side scripting can be used to process form information submitted by a client,
query or update a server-side database, and dynamically generate web pages that
can be displayed in the user's browser.
Server side Scripting language executed from the server machine(system).
User cannot view the original source code by looking at the view source option in
the browser .
User cannot modify the source code.
Example: ASP, PHP, JSP, Python, R, Ruby , Perl etc
.
• Web browsers communicate with web servers using the HyperText Transfer Protocol
(HTTP).
• When you click a link on a web page, submit a form, or run a search, an HTTP request is sent
from your browser to the target server.
• The request includes a URL identifying the affected resource, a method that defines the
required action (for example to get, delete, or post the resource), and may include additional
information encoded in URL parameters (the field-value pairs sent via a query string), as
POST data (data sent by the HTTP POST method), or in associated cookies.
• Web servers wait for client request messages, process them when they arrive, and reply to
the web browser with an HTTP response message. The response contains a status line
indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success).
• The body of a successful response to a request would contain the requested resource (e.g. a
new HTML page, or an image, etc...), which could then be displayed by the web browser.
• The diagram below shows a basic web server architecture for a static site (a static
site is one that returns the same hard-coded content from the server whenever a
particular resource is requested). When a user wants to navigate to a page,
the browser sends an HTTP "GET" request specifying its URL.
• The server retrieves the requested document from its file system and returns an
HTTP response containing the document and a success status (usually 200 OK). If
the file cannot be retrieved for some reason, an error status is returned (see client
error responses and server error responses).
• A dynamic website is one where some of the response content is generated dynamically,
only when needed. On a dynamic website HTML (this is pages are normally created by
inserting data from a database into placeholders in HTML templates a much more efficient
way of storing large amounts of content than using static websites).
• Requests for static resources are handled in the same way as for static sites (static resources
are any files that don't change —typically: CSS, JavaScript, Images, pre-created PDF files
etc).
• Requests for dynamic resources are instead forwarded (2) to server-side code (shown in
the diagram as a Web Application). For "dynamic requests" the server interprets the request,
reads required information from the database (3), combines the retrieved data with HTML
templates (4), and sends back a response containing the generated HTML (5,6).
PHP is a web development language that allows web developers to create
dynamic content that interacts with databases.
PHP stands for Hypertext Preprocessor. It was originally names as Personal Home
page tools.
PHP is server side scripting language which can be embedded in HTML or used as
standalone
It is used to manage dynamic content, databases, session tracking, even build
entire e-commerce sites.
Why PHP?
Easy to lean & Use.
Open source(Cost Efficiency)
Object Oriented Programming
Cross-Platform compatibility(Platform Independent)
Huge & Helpful PHP Community
Features:-
Interpreted
Faster: faster than asp and jsp
Open source:
Platform Independent.
Case Sensitive : PHP is case-sensitive. All the keywords, functions, and class names in
PHP (while, if, echo, else, etc) are not case-sensitive except variables. Only variables
with different cases are treated differently.
Loosely typed language: declaring variables without its data types.
Object oriented Programming
Popular Website build using PHP
Facebook
Yahoo
Wikipedia
Wordpress & Joomla
FlipKart
Basic component for PHP web Development:
AMPP Package(Apache server, MySql, PHP, Perl)
Apache:
• It is free and open-source cross-platform web server software.
• It is not a physical server, but software that runs on a server.
• Its jobs is to establish a connection between a server and the browsers of website visitors
while delivering files back and forth between client and server.
MySql:
• It is free and open-source relational database management system that allows us to
manage relational database.
• MySql is reliable, scalable and fast.
• MySql server provides a DBMS with querying and connectivity capabilities.
• It can handle large databases reliably and quickly in high-demanding production
environment
• PHP code starts with <?php and ends with ?>
• Every PHP statements end with a semicolon (;)
• PHP code are save with .php extension
• PHP contain some HTML tags and PHP code
• We can place PHP code anywhere in our document.
• SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The
script starts with <? and ends with ?>. This will only work by setting
the short_open_tag setting in the php.ini file to ‘on’.
• Comments help in reminding the developer about the code if it’s re-visited after a period of
time.
• A comment is something that is ignored and not read or executed by the PHP engine or the
language as part of a program and is written to make the code more readable and
understandable.
• Single Line Comment: As the name suggests these are single line or short relevant
explanations that one can add to their code. To add this, we need to begin the line with (//)
or (#). Eg: //this is a calling function or #this is a calling function
• Multi-line or Multiple line Comment: These are used to accommodate multiple lines with
a single tag and can be extended to many lines as required by the user. To add this, we need
to begin and end the line with (/*…*/)
• Constants are similar to variables, where once you have defined one, its value is set for the
remainder of the program and cannot be altered.
• To create constant we use define() function
• Syntax : define(name, value, case-insensitive)
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is fals
• Eg: define(“PI”,” 3.1415927”);
• To destroy a variable, pass the variable to PHP’s unset() function.
Eg: $name=“Padmashree”;
echo $name; //display padmashree
unset($name); echo $name //result is: undefined variable
• PHP $$var uses the value of the variable whose name is the value of $var. It means $$ var is
known as reference variable whereas $var is normal variable. It allows us to have a
“variable’s variable.
Eg: $name=“Padmashree”;
$Padmashree=“college”;
echo $name; //Padmashree;
echo $$name; //college;
1) Local Variables : A variable declared inside a function is considered as local.
2) Function Parameter : variables declared inside the parentheses are function parameter.
3) Global Variables : Variables that can be accessed in any part of the program. Global
variables must be explicitly declared by placing the GLOBAL keyword or global in front of
4) Static Variables. The variables declared as function parameters are destroyed on the
function's exit, a static variable will not lose its value when the function exits and will still
hold that value should the function be called again. STATIC keyword is used in front of
variables.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Arithmetic Operators
Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiply both operands
/ Divide numerator by de-numerator
% Modulus Operator and remainder of after an integer division
++ Increment operator, increases integer value by one
Comparison Operators
Example Name Result
$a == $b Equal true if $a is equal to $b after type juggling.
$a === $b Identical true if $a is equal to $b, and they are of the same
type.
$a != $b Not equal true if $a is not equal to $b after type juggling.
$a <> $b Not equal true if $a is not equal to $b after type juggling.
$a !== $b Not identical true if $a is not equal to $b, or they are not of the
same type.
$a < $b Less than true if $a is strictly less than $b.
$a > $b Greater than true if $a is strictly greater than $b.
$a <= $b Less than or equal true if $a is less than or equal to $b.
to
$a >= $b Greater than or true if $a is greater than or equal to $b.
equal to
Logical Operators
Operator Description
and Called Logical AND operator. If both the operands are true then condition
&& becomes true. && has higher precedence than and
or Called Logical OR Operator. If any of the two operands are non zero then
|| condition becomes true. || has higher precedence than or
! Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make false.
xor true if either $a or $b is true, but not both.
Assignment Operators
Example Equivalent Operation
$a += $b $a = $a + $b Addition
$a -= $b $a = $a - $b Subtraction
$a *= $b $a = $a * $b Multiplication
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus
$a **= $b $a = $a ** $b Exponentiation/power
Conditional /Ternary Operators
Operator Description Example
? : Conditional Expression $marks=40; print ($marks>=40) ? "pass" : "Fail";
String Operators
Operator Description Example
. Concatenation $name=$fname.$lname;
.= Concatenation-assignment $fname.=$lname;
If Statement
if($x>0){ echo “ x is positive number”; }
If else Statement
if($x>0){ echo “ x is positive number”; } else{ echo “ x is negative number” ; }
If else if Statement
$marks=69;
if ($marks<33){ echo "fail"; }
else if ($marks>=34 && $marks<50) { echo "D grade"; }
else if ($marks>=50 && $marks<65) { echo "C grade"; }
else if ($marks>=65 && $marks<80) { echo "B grade"; }
else if ($marks>=80 && $marks<90) { echo "A grade"; }
else if ($marks>=90 && $marks<100) { echo "A+ grade“; }
else { echo "Invalid input"; }
Nested if Statement
$age = 23; $nationality = “Nepali";
//applying conditions on nationality and age
if ($nationality == "Indian") {
if ($age >= 18) { echo "Eligible to give vote"; }
else { echo "Not eligible to give vote"; } }
Switch
$day=3;
switch($num){
case 0:
echo(“Sunday");
break;
case 1:
echo(“Monday");
break;
case 2:
echo(“Tuesday");
break;
case 3:
echo(“Wednesday");
break;
case 4:
echo(“Thursday");
break;
case 4:
echo(“Friday ");
break;
default:
echo(“The number is not within the weeks"); }
For Loops
for(initialization; condition; increment/decrement){ for($n=1;$n<=10;$n++){
//code to be executed echo "$n<br/>";
} }
Nest For Loops
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
While Loops
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
do While Loops
$x = 5;
do {
echo “Padmashree College </br>";
$x++;
} while ($x < 10);
Continue
The PHP continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
for ($i =1; $i<=3; $i++) {
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
break
PHP break statement breaks the execution of the current for, while, do-while, switch, and
for-each loop.
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
• An array is a data structure that stores one or more similar type of values in a single value
• An array in PHP is actually an ordered map. A map is a type that associates values to keys.
• An array can be created using the array() language construct. It takes any number of
comma-separated key => value pairs as arguments.
Eg: array( key => value, key2 => value2, key3 => value3, ... )
Types of Array:
Numeric array − These arrays can store numbers, strings and any object but their index
will be represented by numbers. By default array index starts from zero.
Eg: $narray=array(1, 3, 5, 7, 9);
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Eg: $salaries = array(“Mohan" => 2000, “Sohan" => 1000, “Rohan" => 500);
Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices. It is also known as array of arrays.
Eg: $salaries = array(
“BCA“ => array(“Java”, “Scripting language”, “Database”)
“BIT” => array(“AI”, “Robotics Programming”, ”Network Programming”) );
• The foreach construct provides an easy way to iterate over arrays.
• foreach works only on arrays and objects, and will issue an error when you try to use it on a
variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (iterable_expression as $value)
statement
$color=['red', ‘green', 'blue', 'yellow'];
foreach($color as $value){
echo $value."\t";
}
foreach (iterable_expression as $key => $value)
statement
foreach($color as $key=>$value){
echo "$key : \t $value.<br>";
}
count() : This function counts all elements in an array. Eg: echo count($arr);
sort() : This function sorts all the elements in an array. Eg: sort($arr);
array_reverse() : This function returns an array containing elements in reversed order.
Eg: echo array_reverse($arr);
array_search() : This function searches the specified value in an array. It returns key if search
is successful. Eg: echo array_reverse(“java”, $arr);
is_array() : This function checks whether the variable is normal variable or an array.
Eg: echo (is_array($arr))?”is an Array”: “Is not an Array”;
compact() : This function is used to create an array from variables and their values.
Eg: $arr=compact(‘fname’, ’mname’, ‘lname’); print_r($arr);
explode() : This function is used to take a string containing several item separated by a single
character(or string of characters) and place each of these items into an array.
Eg: $arr=explode(‘ ‘,”Padmashree is a It college”); print_r($arr);
A function is a reusable piece or block of code that performs a specific action.
Functions can either return values when called or can simply perform an operation without
returning any value.
Why Function?
Code Reusability:
Better Code organization.
Easy to Understand
Function Type: Inbuilt function & User defined function.
User Defined Function
Function with No Return Type and No Parameters.
Function with No Return Type and Parameters
Function with Return Type and No parameters.
Function with Return Type and Parameters.
Function Call by Value & Call by Reference
• A form is an HTML tag that contains graphical user interface items such as input box, check
boxes radio buttons etc.
• Forms are used to get input from the user and submit it to the web server for processing.
• Creating a form on the webpage is accomplished using HTML, while PHP serves as a
transport for those values from the webpage to the server and then in further processing
those values.
• PHP provides two superglobals and for collecting form-data for processing.
• In the <form> tag, we have two attributes, action and method :
• action: Using this attribute, we can specify the name of the file which will collect and handle
the form-data. In the example above, we have provided name of a Php file.
• method: This attribute specify the means of sending the form-data, whether it will be
submitted via POST method or GET method.
<form action=“formhandler.php" method="POST">
Username: <input type="text" name=“uname"> <br/>
Password: <input type="text" name=“pass"> <br/>
<input type="submit"> </form>
• When a user submits a form Both GET and POST create an array (e.g. array( key1 => value1,
key2 => value2, key3 => value3, ...)) of the values from the input fields. This array holds
key/value pairs, where keys are the names of the form controls and values are the input data
from the user.
• Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means
that they are always accessible, regardless of scope - and you can access them from any
function, class or file without having to do anything special.
• $_GET is an array of variables passed to the current script via the URL parameters.
• $_POST is an array of variables passed to the current script via the HTTP POST method.
• Information sent from a form using GET method is visible to everyone (all variable names
and values are displayed in the URL).
• It has limits on the amount of information to send. The limitation is about 2000 characters.
However, because the variables are displayed in the URL, it is possible to bookmark the page
• So we should never use get for sending passwords or other sensitive information!.
• Information sent from a form with the POST method is invisible to others (all names/values
are embedded/encapsulated within the body of the HTTP request)
• It has no limits on the amount of information to send.
• GET performs are better compared to POST because of the simple nature of appending the
values in the URL Whereas POST has lower performance as compared to GET method
because of time spent in including POST values in the HTTP body.
• The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.
• The PHP $_REQUEST variable can be used to get the result from form data sent with both
the GET and POST methods.
Program : program10_GetPostReq.php
• PHP Date and Time are the functions that generally permit the user to obtain the date and
time from the server where the PHP script runs.
• To keep track of the date and time, PHP uses standard Unix timestamps, which are simply
the number of seconds elapsed since midnight, January 1, 1970. To determine current
timestamp, we can use the time function eg: echo time();
• To obtain timestamp of next week : eg: echo time()+7*24*60*60;
• To create a timestamp for a given date we can use mktime function.
eg: echo time(0,0,0,1,1,2000)// time(hh, mm, ss, month, day,Year);
• To display the date, we use date function.
Syntax : date(format, timestamp)
• date(…) is the function that returns the current timestamp in PHP on the server.
• “format” is the general format which we want our output to be i.e.; it is mandatory.
• “Y-m-d” for PHP date format YYYY-MM-DD
• “Y” to display the current year
• “[timestamp]” is optional. If no timestamp has been provided, PHP will get the current PHP
date time on the server. A timestamp in PHP is a numeric value in seconds between the
current time and value as at 1st January, 1970 00:00:00 Greenwich Mean Time (GMT).
• characters that are recognized in the format parameter string:
DAYS
d Day of the month, 2 digits with leading zeros 01 to 31
j Day of the month without leading zeros 1 to 31
D A textual representation of a day, three letters Mon through Sun
l (lowerc A full textual representation of the day of the week Sunday through Saturday
ase 'L')
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for
Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well
with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for
Saturday)
Month:
F A full textual representation of a month, such as January or January through December
March
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
• characters that are recognized in the format parameter string\
YEARS
L Returns 1 if it’s a leap year and 0 if it is not a leap year 1 if it is a leap
year, 0 otherwise.
Y Returns four digit year format Examples: 1999 or 2003
y Returns two (2) digits year format (00 to 99) Examples: 99 or 03
TIME
Parameter Description Example
“a”, ”A” Returns whether the current time is am or pm, AM <?php echo date("a"); echo
or PM respectively date("A"); ?>
“g”, ”G” Returns the hour without leading zeroes [1 to 12], <?php echo date("g"); echo
[0 to 23] respectively date("G"); ?>
“h”, ”H” Returns the hour with leading zeros [01 to 12],[00 <?php echo date("h"); echo
to 23] respectively date("H"); ?>
“i”, ”s” Returns the minutes/seconds with leading zeroes <?php echo date("i"); echo
[00 to 59] date("s"); ?>
“r” Returns the full date and time <?php echo date("r"); ?>
• Strtotime();
• This function accepts a date/time string, with textual date/time values and parses it as an
Unix timestamp.
<?php
$time1=strtotime("today");
$time2=strtotime("last day of November 2021");
$time3=strtotime("10 months 15 days 10 hours ago");
$time4=strtotime("next month");
$time5=strtotime("third Monday");
$time6=strtotime("yesterday");
$time7=strtotime("now");
echo "<br/>Full Date & Time\t".date('r'); // r returns full date and time
echo "<br/>Hour:\t".date('h'); //h/H returns hour with leading zeroes h [01 to 12],H[00 to 23]
w Open the file for writing only and clears the contents of file. If the file does not
exist, PHP will attempt to create it.
w+ Open the file for reading and writing and clears the contents of file. If the file does
not exist, PHP will attempt to create it.
a Append. Opens the file for writing only. Preserves file content by writing to the
end of the file. If the file does not exist, PHP will attempt to create it.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by
writing to the end of the file. If the file does not exist, PHP will attempt to create
it.
x Open the file for writing only. Return FALSE and generates an error if the file
already exists. If the file does not exist, PHP will attempt to create it.
x+ Open the file for reading and writing; otherwise it has the same behavior as 'x'.
Writing a File
• We can write data to a file or append to an existing file using the PHP fwrite() function
Syntax: fwrite(file pointer, string)
The easiest way to read the entire contents of a file in PHP is with the readfile() function.
This function allows you to read the contents of a file without needing to open
it. readfile($file);
file_get_contents() function is also used to read the whole contents of a file without needing
to open eg: $content = file_get_contents($file); This function accepts the name and
path to a file, and reads the entire file into a string variable.
file_put_contents() function provides an easy method of writing the data to a file without
needing to open it. This function accepts the name and path to a file together with the data
to be written to the file.
rename($file, "laxman.txt") function rename the file name.
unlink($file) function is used to delete the file.
• A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
• enctype='multipart/form-data' -- Your HTML must contain this attribute. If not file will not
be uploaded.
• $_FILES This global contains all the information of the file. Using this $_FILES global, we can
fetch file name, file type, file size, temp file name and errors connected with the file.
Creating an upload script
• There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables −
•$_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
•$_FILES['file']['name'] − the actual name of the uploaded file.
•$_FILES['file']['size'] − the size in bytes of the uploaded file.
•$_FILES['file']['type'] − the MIME type of the uploaded file.
• MySQL is the most popular open source SQL database available which is one of the most
widely used database with PHP, developed, distributed and supported by Sun Microsystem.
• MySQL uses the SQL (Structured Query Language) programming language to work with the
data, and PHP interacts with MySQL by simply passing SQL code through a set of MySQL
functions to the MySQL server, which then returns a result that PHP can interpret.
• MySQL is very fast, reliable, and easy to use.
• Databases: Databases are useful for storing information categorically.
• Database Queries : A query is a question or a request. We can query a database for specific
information and have a record set returned.
PHP with MySQL Database
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension (the "i" stands for improved) : procedural & object oriented.
2. PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was
deprecated in 2012.
• MySQL is the most popular open source SQL database available which is one of the most
Connecting to the server/Establishing connection via PHP : mysqli_connect();
$servername="localhost";
$username="root";
$password="";
$database="student";
$conn=mysqli_connect($servername, $username, $password, $database) or die("Failed!");
• $conn is a database resource type. We use this variable to refer to the connection created.
•This function is used to connect to the database.
Group by :
It is used to group the data or partition the set of tuples into groups based on criteria
Example:
Query: SELECT COUNT(std_name), house FROM stu_group GROUP BY house;
A MySQL subquery is a query nested within another query.
A MySQL subquery is called an inner query while the query that contains the subquery is called an outer
query.
A subquery can be used anywhere that expression is used and must be closed in parentheses.
A sub query is a select query that is contained inside another query.
The inner select query is usually used to determine the results of the outer select query.
Example:
SELECT FN, Address FROM lax WHERE Fee=(SELECT MAX(Fee) FROM lax)
A join clause is used to combine rows from two or more tables, based on a related column
between them.
Different types of SQL JOINS
(INNER) JOIN : Returns records that have matching values in both tables.
LEFT(OUTER) JOIN : Returns all records from the left table, and the matched records from
the right table.
RIGHT(OUTER) JOIN : Returns all records from the right table, and the matched records from
the left table.
FULL OUTER JOIN : Returns all records when there is a match in either left or right table
Table:
Table:
o Select records from the first (left-most) table with matching right table records.
select * from table_order LEFT JOIN customer ON table_order.CustomerID=customer.id;
Selects all records that match either left or right table records.
select * from table_order RIGHT JOIN customer ON table_order.CustomerID=customer.id;
o Select records that have matching values in both tables.