You are on page 1of 57

Server Side Scripting with

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 (/*…*/)

• variable is a name given to a memory location that stores data at runtime.


• The scope of a variable determines its visibility.
• A Php global variable is accessible to all the scripts in an application.
• A local variable is only accessible to the script that it was defined in.
• All variable names must start with the dollar sign e.g. $my_var. This is required to make the
parser faster, as it instantly knows whenever it comes across a variable.
• Variable names are case sensitive; this means $my_var is different from $MY_VAR
• All variables names must start with a letter of the alphabet or the _(underscore) follow
other characters e.g. $my_var1. $1my_var is not a legal variable name.
• Variable names must not contain any spaces, “$first name” is not a legal variable name. You
can instead use an underscore in place of the space e.g. $first_name. You can’t use
characters such as the dollar or minus sign to separate variable names.
• Variable can contain only the character a-z, A-Z,0-9 and _

• Alphanumeric characters are classified as strings.


• Whole numbers are classified integers
• Numbers with decimal points are classified as floating points.
• True or false values are classified as Boolean.
• PHP is a loosely typed language; it does not have explicit defined data types. PHP
determines the data types by analyzing the attributes of data supplied.
• The var_dump function is used to determine the data type.
• Print and Echo is a statement, which is used to display the output.
• We can pass multiple strings separated by comma (,) in echo but we cannot pass multiple
arguments using print
Eg: echo “Padma”,”Shree” ; it is correct.
print “padma”,”Shree” ; it is incorrect.
• Echo statement is faster than print statement so mainly we use echo rather than print.

• 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

the variable. Eg : global $val; or $GLOBALS[‘val’];

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 date('y-m-d H:i:s',$time1);


echo "<br/>".date('y-m-d H:i:s',$time2);
echo "<br/>".date('Y-M-D G:i:s',$time3);
echo "<br/>".date('y-m-d H:i:s',$time4);
echo "<br/>".date('y-m-d H:i:s',$time5);
echo "<br/>".date('y-m-d H:i:s',$time6);
echo "<br/>".date('y-m-d H:i:s',$time7);
?>
Eg:-

echo "<br/>Full Date & Time\t".date('r'); // r returns full date and time

echo "<br/>Hour:\t".date('g'); //g/G returns hour without leading zeroes g[0-12],G[0-24]

echo "<br/>Hour:\t".date('h'); //h/H returns hour with leading zeroes h [01 to 12],H[00 to 23]

echo "<br/>Minutes:\t".date('i'); // i returns minutes with leading zeros

echo "<br/>Second:\t".date('s'); // s returns minutes with leading zeros

echo "<br/>AM/PM:\t".date('a'); // a or A returns am/pm or AM/PM


• The include() and require() statement allows us to include the code contained in a PHP file
within another PHP file.
• Both methods import the content of some other file into the file being executed.
• The only difference between include and require is that require stops the execution of script
if the file is not found whereas include doesn't.
• If the file is missing or inclusion fails, include allows the script to continue but require halts
the script producing a fatal E_COMPILE_ERROR level error.
• Syntax:
<?php
include “filename.php”; OR require “filename.php;
?>
• Include_once/ require_once : is ignored if the requested file has already been included using
any of the four statements
• A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.
• Why and when to use Cookies?
 Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer.
 Personalizing the user experience – this is achieved by allowing users to select their
preferences.
 The page requested that follow are personalized based on the set preferences in the
cookies.
 Tracking the pages visited by a user
• Syntax
setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure],
[httponly]); // only cookie_name and cookie_value are mandatory
 “[domain]” :- it can be used to define the cookie access hierarchy i.e. www.cookiedomain.com
means entire domain while www.sub.cookiedomain.com limits the cookie access
to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a subdomain
of a subdomain as long as the total characters do not exceed 253 characters.
 “[secure]” :- the default is false. It is used to determine whether the cookie is sent via https if it
is set to true or http if it is set to false.
 “[Httponly]” :- If it is set to true, then only client side scripting languages
i.e. JavaScript cannot access them.
• A session is a global variable stored on the server.
• A session is usually a file or database record which contains the small pieces of data which
the web server wants to store for each user. Instead of sending key/value pairs to the
browser, these values are stored on the server.
• Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does not
support cookies, the unique php session id is displayed in the URL.
• On each future request, the browser will send the session ID as cookie and the web server
will located the corresponding session file to allow access to the stored user data.
• Sessions have the capacity to store relatively large data compared to cookies.
• The session values are automatically deleted when the browser is closed. If you want to store
the values permanently, then you should store them in the database.
• Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array
variable.
• Why and When to use Session?
 You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
 You want to pass values from one page to another.
 You want the alternative to cookies on browsers that do not support cookies.
 You want to store global variables in an efficient and more secure way compared to
passing them in the URL
 You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
 session_start(); -> //starting of session
 $_SESSION[name]=value; //assign value to name in session
 echo $_SESSION[name]; //printing session
 unset($_SESSION()); // frees the individual session variables.
 session_destroy(); // removes all the session data including cookies associated with
the session.
• Sending email messages are very common for a web application, for example, sending
welcome email when a user create an account on your website, sending newsletters to your
registered users, or getting user feedback or comment through website's contact form, and
so on.
• We can use the PHP built-in mail() function for creating and sending email messages to
one or more recipients dynamically from your PHP application either in a plain-text form or
formatted HTML. The basic syntax of this function can be given with:
mail($to, s$ubject, $message, [$headers],[$parameters])
• to is the email address of the mail recipient
• $subject is the email subject
• $message is the message to be sent.
• [$headers] is optional, it can be used to include information such as CC, BCC
• CC is the acronym for carbon copy. It’s used when you want to send a copy to an
interested person i.e. a complaint email sent to a company can also be sent as CC to the
complaints board.
• BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses
included in the BCC section will not be shown to the other recipients
<?php
$to = 'laxkrl555@gmail.com';
$subject = 'Project';
$message = 'Dear sir, please find the attached file?';
$from = ‘laxkrl2017@gmail.com';
$headers="from:$from";
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
• PHP is a server side programming language, it allows you to work with files and directories
stored on the web server.
• We can create, access, and manipulate files on web server using the PHP file system
functions.
Opening a File
• The PHP fopen() function is used to open a file. Syntax : $file1=fopen(filename, mode)
Closing a File
• The fclose() function is used to close the file. Syntax: fclose($file1)
Reading a File
• The fread() function can be used to read a specified number of characters from a file.
Syntax : fread(file pointer, length in bytes)
• The fread() function can be used in conjugation with the filesize() function to read the entire
file at once. The filesize() function returns the size of the file in bytes.
Syntax : fread(file pointer, filesize($file));
Note: If you try to open a file that doesn't exist, PHP will generate a warning message. So, to
avoid these error messages you should always implement a simple check whether a file or
directory exists or not before trying to access it, with the PHP file_exists() function.
Mode What it does

r Open the file for reading only.

r+ Open the file for reading and writing.

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.

 Making a query/Retrieving data : mysqli_query();


$result=mysqli_query(query_string, $conn);
 Getting results of query : mysql_fetch_assoc();
while($row = mysql_fetch_assoc($result));

 Closing a connection : mysqli_close();


mysqli_query($conn)
Type Size Description
CHAR[length] Length bytes A fixed length from 0 to 255 characters long
VARCHAR[length] String length+1 bytes A fixed length from 0 to 255 characters long
TINYTEXT String length+1 bytes A string with a maximum length of 255 characters.
TEXT String length+2 bytes A string with a maximum length of 65,535 characters
MEDIUMTEXT String length+3 bytes A string with a maximum length of 16,777,215 characters.
LONGTEXT String length+4 bytes A string with a maximum length of 4,294,967,295 characters.
TINYINT 1 byte Range of -128 to 127 or 0 to 255 unsigned
SMALLINT 2 byte Range of -32,768 to 32767 or 0 to 65535 unsigned
MEDIUMINT 3 byte Range of -83,88,608 to 83,88,607 or 0 to 16,777,215 unsigned
INT 4 byte Range of -2,147,483,648 to 2,147,483,647 or 0 to
4,294,967,295 Unsigned
BIGINT 8 bytes Range of -9,223,372,036,854,775,808 to 9,223,372,036,8
54,775,807 or 0 to 18,446,744,073,709,551,615 unsigned
FLOAT 4 byte A small number with a floating decimal point
DOUBLE 8 bytes A large number with a floating decimal point
Type Size Description
DATE 3 bytes Format: YYYY-MM-DD
DATETIME 8 bytes Format: YYYY-MM-DD HH:MM:SS
TIMESTAMP 4 bytes Format: YYYYMMDDHHMMSS
TIME 3 bytes Format: HH:MM:SS
ENUM 1 or 2 bytes Short for enumeration, which means that each column can have
one of several possible values
SET 1,2,3,4 or 8 bytes Like ENUM except that each column can have more than one of
several possible values.

Difference between CHAR & VARCHAR


 CHAR is fixed length while VARCHAR is variable length. That means, a CHAR(x) string
has exactly x characters in length, including spaces. A VARCHAR(x) string can have up to x characters
and it cuts off trailing spaces, thus might be shorter than the declared length.
 In terms of efficiency, if you are storing strings with a wildly variable length then use a VARCHAR, if the
length is always the same, then use a CHAR as it is slightly faster.
 They also differ in maximum length where the length of a CHAR value can be any value from 0 to 255
and the maximum length of a VARCHAR value is 65,535.
 The INSERT INTO statement is used to insert new records in a table.
 Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Examples:
"INSERT INTO `student_info`(`Stu_id`, `Stu_name`, `Stu_address`, `Stu_phone`, `Stu_email`)
VALUES ('$Stu_id',' $Stu_name',' $Stu_address', '$Stu_phone', '$Stu_email')";

 The SELECT statement is used to select data from a database


 Syntax:
SELECT column1, column2, ...
FROM table_name;
Examples:
"select * from student_info“;

 The WHERE clause is used to filter records.


 It is used to extract only those records that fulfill a specified condition.
 Syntax : Examples:
SELECT column1, column2, ... "select * from student_info
FROM table_name
where college=‘padmashree’ “;
WHERE condition;
 The UPDATE statement is used to modify the existing records in a table..
 Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Examples:
"UPDATE student_info SET Stu_name='$name', Stu_address= '$address', Stu_phone='$phone', Stu_e
mail='$email' WHERE Stu_id='$id' “

 The DELETE statement is used to delete existing records in a table.


 Syntax:
DELETE FROM table_name WHERE condition;
Examples:
"DELETE FROM `student_info` WHERE Stu_id='$Stu_id‘”
 SUM : It is used to total the non-null values in the expression
Query: “select sum(fee) from lax; Result =>

 AVG : It returns the average of the values in a specified column.


Query: “select avg(fee) from lax; Result =>

 COUNT : It returns the total number of values in the specified field.


Query: “select count(fee) from lax; Result =>

 MIN : It returns the smallest value in a specified table field


Query: “select min(fee) from lax; Result =>

 MAX : It returns the largest value in a specified table field


Query: “select max(fee) from lax; Result =>
 Order by :
 The ORDER BY keyword is used to sort the result-set in ascending or descending order.
 It sorts the records in ascending order by default.
 To sort the records in descending order, use the DESC keyword
 Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example:
Query: SELECT * FROM lax ORDER BY Address DESC ;

 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.

SELECT * FROM customer INNER JOIN table_order ON customer.id=table_order.customerid;

You might also like