Web Desing, Programmig and Administration
Web Desing, Programmig and Administration
COURSE CODE:
UNIT 1 : INTRODUCTION
All students should be familiar with the concepts of html and cascading stylesheets.
• A code editor. A code editor is a text editor that is specifically designed for writing code. It
provides features such as syntax highlighting, code completion, and debugging tools. Some
popular code editors include Visual Studio Code, Sublime Text, and Atom.
• A web development environment (WDE). A WDE is a software environment that allows you to
develop web applications locally on your computer. It includes a web server, database server,
and PHP interpreter. Some popular WDEs include WAMP,XAMPP, LAMP, and MAMP.
• A web browser. A web browser is used to view the results of your PHP code. Any modern web
browser, such as Google Chrome, Mozilla Firefox, or Microsoft Edge, will work.
• A version control system (VCS). A VCS is a system that allows you to track changes to your
code and collaborate with other developers. Some popular VCSs include Git and Mercurial.
• A debugger. A debugger is a tool that allows you to step through your code line by line and
inspect the values of variables. This can be helpful for finding and fixing bugs in your code.
Some popular debuggers include Xdebug and PHP Debugger.
• A documentation generator. A documentation generator is a tool that can generate
documentation for your PHP code. This can be helpful for documenting your code and making it
easier to understand and maintain. Some popular documentation generators include
phpDocumentor and Sphinx.
PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used,
free, and efficient alternative to competitors such as Microsoft's ASP.
What is PHP?
It allows web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications.
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.)
What is MySQL?
• MySQL compiles on a number of platforms. PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a
Unix platform). PHP runs on different platforms (Windows, Linux, Unix, etc.)
Three are the main areas where PHP scripts are used:
• Server-side scripting
This is the most used and main target for PHP. You need three things to make this work the way
you need it. The PHP parser (CGI or server module), a web server and a web browser.
You need to run the web server where You can access the PHP program output with a web
browser, viewing the PHP page through the server. All these can run on your home machine if
you are just experimenting with PHP programming.
You can make a PHP script to run it without any server or browser. You only need the PHP
parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on
Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text
processing tasks.
PHP may not the very best language to create a desktop application with a graphical user
interface, but if you know PHP very well, and would like to use some advanced PHP features in
your client-side applications you can also use PHP-GTK to write such programs. You also have
the ability to write cross-platform applications this way. In this article, we’ll have a detailed look
at the server-side scripting using PHP.
Why PHP?
A web server is an information technology that processes requests via HTTP, the basic network
protocol used to distribute information on the World Wide Web. There exist many types of web
servers that servers use. Some of the most important and well-known are: Apache HTTP Server,
IIS (Internet Information Services), lighttpd, Sun Java System Web Server etc. As a matter of
fact, PHP is compatible with all these web servers and many more.
Unlike some technologies that require a specific operating system or are built specifically for
that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux, Unix etc)
An important reason why PHP is so used today is also related to the various databases it supports
(is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo, MaxDB,
MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so on.
Anyone can start using PHP right now by downloading it from php.net. Millions of people are
using PHP to create dynamic content and database-related applications that make for outstanding
web systems. PHP is also open source, which means the original source code is made freely
available and may be redistributed and modified.
PHP is a simple language to learn step by step. This makes it easier for people to get engaged in
exploring it. It also has such a huge community online that is constantly willing to help you
whenever you’re stuck (which actually happens quite a lot).
• Laravel
• Symfony
• Yii
• CodeIgniter
• Laminas Project (formerly Zend Framework)
• CakePHP
• Phalcon
• Slim Framework
• FuelPHP
• PHPPixie
• Fat-Free Framework
• Supported versions:
Advantages of PHP
• It’s fast. Because it is embedded in HTML code, the response time is short.
• It’s inexpensive — free, in fact. PHP is proof that free lunches do exist and that you can
get more than you paid for.
• It’s easy to use. PHP contains many special features and functions needed to create
dynamic Web pages. The PHP language is designed to be included easily in an HTML
file.
• It can run on many operating systems. It runs on a variety of operating systems —
Windows, Linux, Mac OS, and most varieties of Unix.
• It’s available on almost all Web hosts. If you are going to publish your Web site on a
Web host, you will find PHP installed on almost all Web hosts for free.
• Technical support is widely available. A large base of users provides free support
through e-mail discussion lists.
• It’s secure. The user does not see the PHP code.
• It’s designed to support databases. PHP includes functionality designed to interact
with specific databases. It relieves you of the need to know the technical details required
to communicate with a database.
• It’s customizable. The open source license allows programmers to modify the PHP
software, adding or modifying features as needed to fit their own specific environments
Learning a new language is not easy. You need to understand not only the syntax of the
language, but also its grammatical rules, that is, when and why to use each element of the
language
PHP code is executed on the server, and the plain HTML result is sent to the browser.
For maximum compatibility, we recommend that you use the standard form
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code
There are four ways the PHP parser engine can differentiate PHP code in a webpage:
• Canonical PHP Tags This is the most popular and effective PHP tag style and looks like this:
<?php…..?>
• Short-open Tags
These are the shortest option, but they might need a bit of configuration, and you might either
choose the --enable-shorttags configuration option when building PHP, or set the short_open_tag
setting in your php.ini file.
• ASP-like Tags
In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%.........%>
You can define a new script with an attribute language like so:
<script language=”php”>……..</script>
The result of the above statements would be the same: "Hello World". But why are there three
different ways to output?
echo and print are more or less the same. They are both used to output data to the screen. The
differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another. There are two basic statements to output text
with PHP: echo and print. In the example above we have used the echo statement to output the
text "Hello World"
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.
Commenting PHP
Just like other languages, there are several ways to comment PHP code.
Let’s have a look at the most useful ones:
Variables in PHP
Variables are the building blocks of any programming language. A variable can be thought of as
a programming construct used to store both numeric and nonnumeric data. The contents of a
variable can be altered during program execution, and variables can be compared and
manipulated using operators.
A variable is used to store information. Variable names in PHP are case-sensitive. As a result the
variables $color, $Color and $COLOR are treated as three different variables.
Variables are used for storing values, like text strings, numbers or arrays. When a variable is
declared, it can be used over and over again in your script.
$var_name = value;
1. Integers -
▪ They are whole numbers, without a decimal point, like 4195.
▪ They are the simplest type.
▪ They correspond to simple whole numbers, both positive and negative.
Integers can be assigned to variables, or they can be used in expressions,
like $int_var = 12345;$another_int = -12345 + 12345;
▪ Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base
16) format. Decimal format is the default, octal integers are specified with
a leading 0, and hexadecimals have a leading 0x.
2. Doubles –
▪ floating-point numbers like 46.2, 733.21 etc
▪ They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed.
3. Booleans -
▪ They have only two possible values either true or false.
▪ PHP provides a couple of constants especially for use as Booleans: TRUE
and FALSE,
4. Strings - set of characters, like KIUT
5. Arrays - named and indexed collections of other values
There are numerous functions available for determining the data type of variables
• getType( )
• is_array( )- Returns true if the argument is an array
• is_double( )- Returns true if the argument is a double
• is_float( ), is_real( )
• is_long( ),
• is_int( )-Returns true if the argument is an integer
• is_string( )- Returns true if the argument is a string
• is_object( )- Returns true if the argument is an object
• is_resource( )- Returns true if the argument is a resource
• is_null( )- Returns true if the argument is null
• is_scalar( ) – check for integer, Boolean, string, or float
• is_numeric( ) – check for number or numeric string
• is_callable( ) – checks for valid function name
• is_bool() -Returns true if the argument is boolean
There is also a settype( $var, ‘type’ ) function that can be used to set a specific type
// Casting
$totalamount = (float)$totalqty;
The following snippet shows all of these data types declared as variables:
<?
$intNum = 472;
$doubleNum = 29.3;
$boolean = true;
$string = ’bcs’;
class person {
function agePrint() {
$age = 5;
?>
• A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and
_)
Variable Scope
• At this point we know that all variables have an identifier, a data type, and a value.
• All variables also have a scope.
o The scope of a variable refers to the places in a script where a variables can be
used.
In PHP, variables can be declared anywhere in the script. The scope of a variable
is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$x = 5; // local scope
PHP can be used for creating dynamic websites. In a dynamic website, user can
interact with website by providing text or by selecting options. Form is one of the
quickest and easiest ways to add interactivity to our website. Through forms we
can read user data into PHP variables.
Sample form
Home.html
< html>
< head>
< body>
< form action=" message . PHP" method =" post"> Enter your message:
</ form>
</ body>
</ html>
Message. php
<? PHP
// print it
?>
Output
Explanation
Here we have used HTML coding for displaying the input box. The <form> tag of
html isused with input option. The form tag also contains two main attributes
action and method.
The action attribute specifies the name of the script. Here the name is
message.php. The script will process the message entered into the form. The
method attribute of the < form> tag specifies the manner in which form data will
be submitted. Here it is POST method.
We have to run the home.html file in a browser. This is a client side script. On
running this file a form is displayed in the webpage with a line.When we click the
submit button the server side script in the action attribute will be called for
execution. That script will display another webpage that prints the string we have
entered.The $_POST variable would have stored the string we have entered. It
will be stored in $_POST[‘msg’]. Then it will be assigned to php variable
$input.We can display it using echo statement
Constants
Constants are like variables except that once they are defined they cannot be
changed or undefined.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name). Note: Unlike variables, constants are automatically global across
the entire script.
Syntax
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
echo “GREETING”;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
echo greeting;
?>
</body>
</html>
NOTE
Constants are automatically global and can be used across the entire script.
Operators
a. Arithmetic Operators
b. Assignment Operators
c. Bitwise Operators
d. Comparison Operators
e. Incrementing/Decrementing Operators
f. Logical Operators
g. String Operators
h. Array Operator
The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
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.
Comparison Operators
The increment and decrement operators are used to increase and decrease the
value of a variable.
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.
String Operators
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
For example the expression 3+2*3 will first evaluate the product 2*3 and then the
sum, so the result is 9 rather than 15. If you want to perform operations in a
specific order, different from the natural order of precedence, you can force it by
enclosing the operation within parentheses. Hence, (3+2)*3 will first perform the
sum and then the product, giving the result 15 this time
Control structures
▪ Control structure allows you to control the flow of code execution in your
application.
▪ Generally, a program is executed sequentially, line by line, and a control
structure allows you to alter that flow, usually depending on certain
conditions
▪ Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
▪ Conditional statements are statements that can only be executed when a certain particular
condition is fulfilled.
a) The If statement
The if statement executes a piece of code if a condition is true. The syntax is
if (condition)
{
// code to be executed in case the condition is true
}
<?php
$age = 18;
if ($age < 20)
{
echo "You are a teenager";
}
?>
b) if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Example
<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
c) if...elseif....else Statement
If you've got more than two choices to choose from, you can use the elseif statement.
Syntax
if (expression1)
{
// code is executed if the expression1 evaluates to TRUE
}
elseif (expression2)
{
// code is executed if the expression2 evaluates to TRUE
}
elseif (expression3)
{
// code is executed if the expression3 evaluates to TRUE
}
else
{
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a
default choice
}
Example
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically. The default
statement is used if no match is found.
Example 1
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
Example 2
<?php
$domain = 'sk';
switch ($domain) {
case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}
Looping Statements
Computers often have to do the same task repetitively until some condition is
satisfied. loops are used to execute the same code block for a specified number of times.
The for loop is used when the programmer knows in advance how many times the block
of code should be executed. This is the most common type of loop encountered in almost
every programming language.
Syntax
• initiliation: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).
Example
An example where we use the for loop would be:
<html>
<body>
<?php
for ($i=0; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Syntax
while (condition)
{
code to be executed;
}
The do...while statement will always execute the block of code once, it will then check
the condition,and repeat the loop while the condition is true.
Its also called an exit controlled loop
Syntax
do
{
code to be executed;
}
while (condition);
example
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
d) foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
The following example demonstrates a loop that will output the values of the
given array ($colors):
example
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) ``
{
echo "$value <br>";
}
?>
</body>
</html>
Arrays
Array is complex variable that enables us to store multiple values in a single variable. We use
this to store related information. An array is a special variable, which can hold more than one
value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
The solution is to create an array! An array can hold many values under a single name, and you
can access the values by referring to an index number.
or
the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
Associative arrays are arrays that use named keys that you assign to them.
Also known as hash arrays
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
To loop through and print all the values of an associative array, you could use a
foreach loop, like this:
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.
The dimension of an array indicates the number of indices you need to select an
element.
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,descending or
ascending.
The following example sorts the elements of the $numbers array in ascending
numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>
The following example sorts the elements of the $numbers array in descending
numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>
1. Reducing repetition:
User defined function enables developer to extract commonly used pieces of code as separate
package. These functions help developers avoid redundant work and focus more on the logic
rather than routine things.
2. Easy maintenance:-
Because functions are defined once and used many times, they are used to maintain the code.
During code maintenance if we want to change from values in calculation, we need to change
only in the function. We need not Traverse the whole program for making change in one value.
3. Improves abstraction:
Function forces programmer to think in abstract terms. We need not worry about implementation
of the function. It is enough that we know the function name, number of arguments and return
type of the function.
• Built-in functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform
a specific task
• Creating a Function
• Calling a Function
<?php
// code to be executed
?>
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and }, the arguments within the function are optional.
invoking function
<?php
….
….
displayShakesphearQuote();
?>
PHP functions are defined with the function keyword following by name of the function.
➢ The name of function should follow the rule for naming variables.
➢ The function code can contain any valid PHP statements, which includes loops conditional
statements and call to other function.
➢ If the function had arguments we have to specify the arguments during invoking
Example
<?php
//define a function
function displayQuote()
echo’some are born great, some achieve greatness and some have greatness through upon them’;.
displayQuote();
?>
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters as you like.
<?php
//define a function
$area=$base*$height*0.5
return $area;
$ta=triangle_area(10,50);
?>
<?php
function greetPerson($name)
greetPerson("Michael");
?>
example
<?php
echo "";
echo "";
echo "";
?>
A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Example:
<html>
<head>
</head>
<body>
<?php
return $sum;
?>
</body>
</html>
Basically, an error is a mistake in a program that may be caused by writing incorrect syntax or
incorrect code. An error message is displayed on your browser containing the filename along
with location, a message describing the error, and the line number in which error has occurred.
There are usually different types of error. In PHP, mainly four types of errors are considered:
2. Fatal Error
3. Warning Error
4. Notice Error
A syntax error is a mistake in the syntax of source code, which can be done by programmers due
to their lack of concern or knowledge. It is also known as Parse error. Compiler is used to catch
the syntax error at compile time.
Fatal Error
A fatal error is another type of error, which is occurs due to the use of undefined function. The
PHP interpreter understands the PHP code but also recognizes the undefined function. This
means that when a function is called without providing its definition, the PHP interpreter
generates a fatal error.
Warning Error
Notice Error
Notice error is same as warning error. When a program contains something wrong, the notice
error occurs. But it allows/continue the execution of the program with a notice error. Notice error
does not prevent the execution of the code. For example - access to undefined variable.
Advantage of the function are realised when the function or statement calling the function
remains in the same script (same PHP file). we can also use function that can be defined in other
PHP files by importing the function definition.
(i) include()
(ii) require()
Eg:
Using include()
<?php
//import file
?>
Include function generates warning message if the value in the file or function cannot
be found but the execution of script continues. The include() function takes all the content in a
specified file and includes it in the current file.
Assume we have a standard menu file, called "menu.php", that should be used on all pages:
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
</html
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
</div>
<p>Some text.</p>
</body>
</html>
Using include_once
Each time you issue the include directive, it includes the requested file again, even if you’ve already
inserted it. For instance, suppose that library.php contains a lot of useful functions, so you include it in
your file. Now suppose you also include another library that includes library.php. Through nesting,
you’ve inadvertently included library.php twice. This will produce error messages, because you’re trying
to define the same constant or function multiple times. To avoid this problem, use include_once instead.
include_once "library.php";
?>
Require function:-
Ex:-
<?php
//import files
?>
The require function forces file to be included in the script. If the file or function cannot be
<?php
require_once "library.php";
?>
Global variable can be used in PHP script for counting the number of visitors in a website. This
is done by the following statement.
Global $count
They are
1.$_SERVER is a super global variable which holds information about headers, paths and script
locations.
Eg.
<?php
Echo $_SERVER[‘PHP_SELF’];
Echo $_SERVER[‘SERVER_NAME’];
Echo “<br>”;
Echo $_SERVER[‘HTTP_HOST’];
Echo “<br>”;
$_SERVER[‘HTTP_REFERER’];
Echo “<br>”;
Echo $_SERVER[‘HTTP_USER_AGENT’];
?>
2. $_POST
Used to collect data after submitting HTML form with method =" post"
html>
<body>
?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
3. $_GET
Collect form data after submitting HTML form with method = "GET"
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
4.$_REQUEST
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
5.$_GLOBALS
<?php
function test() {
$foo = "local variable";
6.$_FILES –
It contains names, sizes, and mime types of files uploaded in the current HTTP request.
<?php
echo "Filename: " . $_FILES['file']['name']."<br>";
echo "Type : " . $_FILES['file']['type'] ."<br>";
echo "Size : " . $_FILES['file']['size'] ."<br>";
echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
echo "Error : " . $_FILES['file']['error'] . "<br>";
?>
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
8.$_COOKIE-
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those type of systems.
Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different
tables and relations are established using primary keys or other keys known as Foreign Keys.
RDBMS Terminology
Database languages are used to read, update and store data in a database. There are
several such languages that can be used for this purpose; one of them is SQL
(Structured Query Language).
• CREATE DATABASE
• CREATE TABLE
CREATE TABLE:
The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of
rows and columns. So while creating tables we have to provide all the information to SQL about the
names of the columns, type of data to be stored in columns, size of the data etc.
Let us now dive into details on how to use CREATE TABLE statement to create tables in SQL.
Syntax:
Example Query:
This query will create a table named Students with three columns, ROLL_NO, NAME and SUBJECT.
ii) DROP:
The DROP statement destroys the objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database management system
(RDBMS).
The TRUNCATE TABLE mytable statement is logically (though not physically) equivalent to the
DELETE FROM mytable statement (without a WHERE clause).
DROP vs TRUNCATE
Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
Truncate preserves the structure of the table for future use, unlike drop table where the table is deleted
with its full structure.
Table or Database deletion using DROP statement cannot be rolled back, so it must be used wisely.
DROP DATABASE student_data; After running the above query whole database will be deleted.
It is also used to add and drop various constraints on the existing table.
ADD is used to add columns into the existing table. Sometimes we may require to add additional
information, in that case we do not require to create the whole database again, ADD comes to our rescue.
Syntax:
is used to drop column in a table. Deleting the unwanted columns from the table.
Syntax:
It is used to modify the existing columns in a table. Multiple columns can also be modified at once.
ALTER TABLE table_name MODIFY column_name column_type;
QUERY:
v) Comments
As is any programming languages comments matter a lot in SQL also. In this set we will learn about
writing comments in any SQL snippet.
The SQL commands that deals with the manipulation of data present in the database belong to DML or
Data Manipulation Language and this includes most of the SQL statements.
i) SELECT Statement
select statement is used to fetch data from relational database. A relational database is organized
collection of data. As we know that data is stored inside tables in a database.
SQL select statement or SQL select query is used to fetch data fro m one or more than one tables.
SELECT One column: Here column_name is the name of the column for which we need to fetch data
and table_name is the name of the table in the database.
Example:
Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:
The INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using
INSERT INTO statement for inserting rows:
a)Only values: First method is to specify only the value of data to be inserted without the column names.
b)Column names and values both: In the second method we will specify both the columns which we
want to fill and their corresponding values as shown below:
INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..); \
iii).UPDATE Statement
The UPDATE statement in SQL is used to update the data of an existing table in database. We can update
single columns as well as multiple columns using UPDATE statement as per our requirement. Basic
Syntax:
EX1: SQL> UPDATE EMPLOYEES SET EMP_SALARY = 10000 WHERE EMP_AGE > 25;
The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single
record or multiple records depending on the condition we specify in the WHERE clause.
Basic Syntax:
Delete the rows where NAME = ‘Ram’. This will delete only the first row. DELETE FROM Student
WHERE NAME = 'Ram';
Deleting multiple records: Delete the rows from the table Student where Age is 20. This will delete 2
rows(third row and fifth row).
DELETE FROM Student WHERE Age = 20; Delete all of the records:
DCL includes commands such as GRANT and REVOKE which mainly deals with the rights, permissions
and other controls of the database system.
ii). REVOKE-withdraw user’s access privileges given by using the GRANT command.
TCL commands deals with the transaction within the database. Examples of TCL commands:
JOINS IN RDBMS
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
Join in DBMS is a binary operation which allows you to combine join product and selection in one single
statement.
The goal of creating a join condition is that it helps you to combine the data from two or more DBMS
tables. The tables in DBMS are associated using the primary key and foreign keys.
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is
satisfied. It returns the combination of all rows from both the tables where the condition satisfie
Query
Example
EMPLOYEE Table
The SQL left join returns all the values from left table and the matching values from the right table. If
there is no matching join value, it will return NULL.
Syntax
Query
4.RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched
values from the left table. If there is no matching in both tables, it will return NULL.
Query
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have all the
records from both tables. It puts NULL on the place of matches not found.
Query
Output
• MySQL is released under an open-source license. So you have nothing to pay to use it.
• MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL works on many operating systems and with many languages
• including PHP, PERL, C, C++, JAVA, etc.
• MySQL works very quickly and works well even with large data sets.
• MySQL is very friendly to PHP, the most appreciated language for web development.
• MySQL supports large databases, up to 50 million rows or more in a
• table. The default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).
• MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific
environments.
MySQL uses many different data types broken into three categories −
• Numeric
• Date and Time
• String Types.
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you.
The following list shows the common numeric data types and their descriptions −
INT
A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a
width of up to 11 digits.
TINYINT
A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If
unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
MEDIUMINT
BIGINT
A large integer that can be signed or unsigned. If signed, the allowable range
is from -
20 digits.
FLOAT(M,D)
display length (M) and the number of decimals (D). This is not required and
will default to 10,2, where 2 is the number of decimals and 10 is the total
for a FLOAT.
DOUBLE(M,D)
A double precision floating-point number that cannot be unsigned. You can define the display length (M)
and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of
decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
An unpacked floating-point number that cannot be unsigned. In the unpacked decimals, each decimal
corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required.
NUMERIC is a synonym for DECIMAL.
DATE
A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th,
1973 would be stored as 1973-12-30.
DATE TIME
A date and time combination in YYYY-MM-DD HH:MM:SS format,between 1000-01-01 00:00:00 and
9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as
1973-12-30 15:30:00.
TIME STAMP
A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like the previous
DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December
30th, 1973 would be stored as 19731230153000 (YYYYMMDDHHMMSS).
TIME
YEAR(M)
Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR
can be between 1970 to 2069 (70 to 69).
If the length is specified as 4, then YEAR can be 1901 to 2155. The default length is 4.
String Types
Although the numeric and date types are f un, most data you'll store will be in a string format. This list
describes the common string datatypes in MySQL.
CHAR(M)
A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with
spaces to the specified length when stored. Defining a length is not required, but the default is 1.
VARCHAR(M)
example, VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT
A field with a maximum length of 65535 characters. BLOBs are"Binary Large Objects" and are used to
store large amounts of binary data,
such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The
difference between the two is that the sorts and comparisons on the stored data are case sensitive on
BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
TINYBLOB or TINYTEXT
A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with
TINYBLOB or TINYTEXT.
MEDIUMBLOB or MEDIUMTEXT
A BLOB or TEXT column with a maximum length of 16777215 characters. You do not specify a length
with MEDIUMBLOB orMEDIUMTEXT.
LONGBLOB or LONGTEXT
A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a
length with LONGBLOB or LONGTEXT.
ENUM
An enumeration, which is a fancy term for list. When defining an ENUM, you are
creating a list of items from which the value must be selected (or it can be
NULL). For example, if you wanted your field to contain "A" or "B" or "C",
you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever
populate that field.
mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation
mysqli_character_set_name() Returns the default character set for the database connection
mysqli_connect_errno() Returns the error code from the last connection error
mysqli_connect_error() Returns the error description from the last connection error
mysqli_errno() Returns the last error code for the most recent function call
mysqli_error_list() Returns a list of errors for the most recent function call
mysqli_error() Returns the last error description for the most recent function call
mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both
mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object
mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set
mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result set
mysqli_field_count() Returns the number of columns for the most recent query
mysqli_get_host_info() Returns the MySQL server hostname and the connection type
Connect to a Database
Before you can access data in a database, you must create a connection to the database.
Syntax
mysql_connect(servername,username,password);
Parameter Description
Servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
Username Optional. Specifies the username to log in with. Default value is the name of the user
that owns the server process
we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if
the connection fails:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
// some code
?>
Example 2
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
?>
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(PDOException $e) {
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before, use
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
mysql_close($con);
?>
Config.php
<?php
$dbuser="root";
$dbpass="";
$host="localhost";
$dbname = "test";
?>
Index.php
include_once('config.php');
if(isset($_POST['signup']))
//Getting Values
$fname=$_POST['fullname'];
$email=$_POST['email'];
$mobile=$_POST['mobilenumber'];
$pass=$_POST['password'];
$stmt = $mysqli->prepare($result);
$stmt->bind_param('s',$email);$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
if($count>0)
echo "<script>alert('Email id already associated with another account. Please try with diffrent
EmailId.');</script>";
else {
$stmti = $mysqli->prepare($sql);
$stmti->bind_param('ssis',$fname,$email,$mobile,$pass);
$stmti->execute();
$stmti->close();
?>
<?php session_start();
include_once('config.php');
if(isset($_POST['login']))
//Getting Values
$email=$_POST['email'];
$pass=$_POST['password'];
$stmt->bind_param('ss',$email,$pass);
$stmt->execute();
$stmt->bind_result($FullName,$id);
$stmt->close();
else {
$_SESSION['fname']=$FullName;
$_SESSION['uid']=$id;
header('location:welcome.php');
?>
Welcome.php
<?php session_start();
if(strlen($_SESSION['uid'])==0)
header("Location:logout.php"); }
else{
?>
The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:
Input Validation
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
We will also do two more things when the user submits the form:
Strip unnecessary characters (extra space, tab, newline) from the user input
data (with the PHP trim() function).Remove backslashes (\) from the user input data (with the
PHP stripslashes ()function
The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).We will name the function
test_input().
Now, we can check each $_POST variable with the test_input() function, and the script looks
like this:
EXAMPLE
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
} else {
$name = test_input($_POST["name"]);
if (empty($_POST["email"])) {
} else {
$email = test_input($_POST["email"]);
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
if (empty($_POST["gender"])) {
} else {
$gender = test_input($_POST["gender"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
?>
<br><br>
<br><br>
<br><br>
<br><br>
Gender:
<br><br>
</form>
</body>
</html>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has
been submitted - and it should be validated. If it has not been submitted, skip the validation and
display a blank form.
However, in the example above, all input fields are optional. The script works fine even if the
user does not enter any data.
The next step is to make input fields required and create error messages if needed.