Click here for Getting Offer
if you want to download this handouts in pdf form then Go to pdf/ppt and then select pdf thanks.
What is Internet?
• The Internet is a worldwide collection of computer networks
connecting academic, governmental, commercial, and
organizational sites.
• It provides access to communication services and
information resources to millions of users around the globe.
• Internet services include:
• direct communication (e-mail, chat)
• online conferencing (Usenet News, e-mail discussion
lists)
• remote login and file transfer (telnet, ftp)
• and many other valuable tools and resources
→ The Internet and the WWW are not synonyms
• WWW also known as the Web
• Collection of hyperlinked text documents,
audio, and video files, and remote sites etc.
Accessed via Internet, computers can contact
each other
Public files on computers can be read by
remote user
◦ usually Hypertext Markup Language (.html)
URL - Universal Resource Locator - is name
of file on a remote computer
http://www.microsoft.com
Web Page
◦ Each page available on the website is called a web page.
◦ It is usually written in Hypertext Markup Language (HTML).
◦ It contains text, graphics, images, videos and may also contain
hyperlinks to other web pages.
◦ It is identified by a unique URL (Uniform Resource Locator).
URL is the the unique address of any document available on the
web.
Website
◦ A collection of several related web pages written in HTML markup
language.
Home Page
◦ The first page of any website is called home page.
Web Server
A machine that responds to client requests and sends the requested page
back to user.
popular web server software:
• Apache: www.apache.org
• Web Browser
• Web browser is a software tool used to access and search
information on web.
• Some of popular web browser software are:
• Mozilla Firefox: getfirefox.co
• Microsoft Internet Explorer (IE): part of Windows
• Apple Safari: part of Mac OS X
• Opera: opera.com
• Google Chrome
• Hypertext Markup Language (HTML/XHTML):
• used for writing web pages
• Cascading Style Sheets (CSS):
• supplies stylistic info to web pages
• JavaScript: allows to program the behavior of web pages
• Hypertext Preprocessor (PHP): allows the web server to create pages
dynamically
• Structured Query Language (SQL): interaction with databases
Personal websites
◦ These websites are used by people for their personal use such as to
share information about themselves or their products, to enhance their
skills or post their curriculum vitae online to improve their chances of
getting a job.
◦ Another most common use is to publish virtual journals called blogs that
describe events in people’s lives, their interests and their personal
opinions on different topics.
Professional websites
◦ These are created as portals that provide platform for businesses and
provide information on their products and services. Some of these portals
enable businesses to sell products online and act as virtual storefronts
for receiving orders and payment.
◦ Such sites can directly generate revenue for businesses.
Static websites are developed with fixed-content pages that do not contain
any programmatically controlled content.
Fixed contents pages are pages with content that does not change
dynamically.
The content will only change when the website designer manually modifies
it.
Dynamic websites are driven by dynamic content that is loaded or created
using programming and databases.
Database
◦ Collection of related data stored on a
particular topic
◦ Storage and retrieval is in an organized and
efficient way
◦ Examples: Hospital database, Library
database, Student database etc.
Database Management System (DBMS)
◦ Collection of programs that allows users to
create and maintain a database
◦ Examples: MS Access, MySQL, DB2, SQL
Server etc.
Ø Databases are established technology for managing large
amounts of data.
Ø Achieving complete separation between your site's design and the
content you want to present.
Ø Interaction in real time
A database-driven Web site is a
Web site that uses a database to
gather, display, or manipulate
information
Examples:
◦ News sites: CNN.com and
MSNBC.com
◦ E-commerce companies:
Amazon.com, which is a Web
interface of a big-sized
database system containing
customer and transactional
information.
Client
(Browser)
Web
Server
Database
Server
HTTP request
SQL query
SQL result
HTML page
◦ Databases
MS Access
MySQL, mSQL
Oracle, Sybase, MS SQL Server
◦ Integration tools
PHP or CGI, Servlets, JSP, ASP etc.
• Hyper Text Markup Language
• Syntax
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
• An HTML table is used to organize data in the form of rows and columns.
• The <table> tag is used to create a table in HTML.
• The table rows are created using <tr> tag and <td> tag is used to create
data cells.
• Table headings can be created using <th> tag.
• The <caption> tag is used to set the title for the table at the top of table.
• The border is an attribute of <table> tag which is used to put a border
across all the cells of the table.
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<table border="1">
<caption>This is Sample Table.</caption>
<th>Heading 1</th>
<th>Heading 2</th>
<tr>
<td>This is Row 1, This is Column 1</td>
<td>This is Row 1, This is Column 2</td>
</tr>
<tr>
<td>This is Row 2, This is Column 1</td>
<td>This is Row 2, This is Column 2</td>
</tr>
</table>
</body>
</html>
Output
• The background of a table can be set using any of the following two ways:
• bgcolor attribute : Using this attribute, you can set background color of the
table.
• background attribute :Using this attribute, you can set background image.
• bordercolor attribute: Using this attribute, you can set border color.
• Syntax
• Update the <table> tag of above code as given below then see the
output.
• <table border="1" bordercolor="red" bgcolor="yellow">
• Output:
• colspan attribute is used to merge two or more columns into a single column.
• Rowspan is used merge two or more rows.
• Syntax
• <TH COLSPAN = “2”>
• <TD ROWSPAN = “2”>
• Example
<table border="1">
<caption>This is Sample Table.</caption>
<th colspan= "2">Heading 1</th>
<tr>
<td>This is Row 1, This is Column 1</td>
<td>This is Row 1, This is Column 2</td>
</tr>
<tr>
<td>This is Row 2, This is Column 1</td>
<td>This is Row 2, This is Column 2</td>
</tr>
</table>
• HTML Forms are required when you want to collect some data from the site
visitor. For example during user registration you would like to collect
information such as name, email address, credit card, etc.
• A form will take input from the site visitor and then will post it to a back-end
application such as CGI, ASP Script or PHP script etc. The back-end
application will perform required processing on the passed data based on
defined business logic inside the application.
• <form> and </form> tags are used to created form; all form controls are
placed in between these opening and closing tags.
• A form tag usually consists of following attributes:
• Action: “url”
• It specifies the location where we have to send our data when Submit
button is clicked.
• method="get“ or “Post”
• Get for search forms and forms where results need to be retrieved.
• Post for feedback forms and forms where results need to be sent.
• target="target"
• This specifies where our page will be opened
• target= _blank means open page in a new window
• target= _top means open the page in the same window
• Following are some commonly used attributes for input fields.
• MAXLENGTH
• Allows to specify the maximum number of characters a user can enter
into the text box.
• NAME
• Used to give a name to the control which is sent to the server to be
recognized and get the value.
• TYPE
• Indicates the type of input control and for text input control it will be set
to text.
• VALUE
• This can be used to provide an initial value inside the control.
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form action="demo.php" method="get">
Name: <input type="text" name="name"><br>
Father Name: <input type="text" name="fname"><br>
Gender: <input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="male"> Male <br>
Email Address: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Before you continue you should have a basic
understanding of the following:
HTML
CSS
JavaScript
PHP is an abbreviation for "PHP: Hypertext
Preprocessor"
PHP is a widely used, open source scripting
language
PHP scripts are executed on the server
PHP is free to download and use
PHP files can contain text, HTML, CSS,
JavaScript, and PHP code
PHP code are executed on the server, and the
result is returned to the browser as plain
HTML
PHP files have extension ".php"
PHP runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers
used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP
resource: www.php.net
PHP is easy to learn and runs efficiently on
the server side
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and
close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your
database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML.
You can output images, PDF files, and even
Flash movies. You can also output any text,
such as XHTML and XML.
To start using PHP, you can:
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then
install PHP and MySQL
If your server has activated support for PHP
you do not need to do anything.
Just create some .php files, place them in
your web directory, and the server will
automatically recognize them and execute.
You do not need to compile anything or
install any extra tools.
Because PHP is free, most web hosts offer
PHP support.
If your server does not support PHP, you must:
install a web server
install PHP
install a database, such as MySQL
The official PHP website (PHP.net) has
installation instructions for
PHP:http://php.net/manual/en/install.php
PHP program can be run under various like
WAMP, XAMPP etc.
WAMP Server: this server is a web
development platform which helps in creating
dynamic web applications.
XAMPP Server: It is a free open source crossplatform web server package.
you can download it from the following link:
http://www.apachefriends.org/en/xamppwindows.html
After downloading, just follow the following
step to start xampp server:
Step1
Install XAMPP
Step2
Assume you installed xampp in C Drive.
Go to: C:\xampp\htdocs
Create your own folder, name it for example
as PHPCode.
Step3
Now create your first php program in xampp
and name it as “add.php”:
<html>
<head><title>Addition php</title></head>
<body>
<?php # operator
print "<h2>php program to add two
numbers...</h2><br />";
$val1 = 20;
$val2 = 20;
$sum = $val2 + $val2; /* Assignment operator */
echo "Result(SUM): $sum"; ?>
</body>
</html>
Step4
Now double click on “XAAMP CONTROL
PANEL” on desktop and START “Apache”
(icon also appears on the bottom)
(XAAMP Control Panel Screenshot is on next
slide)
Step5
Type localhost on your browser and press
enter:
It will show the following Screen:
Step6
Now type the following on browser:
http://localhost/ PHPCode /
Below screenshot shows php files created
under folder “PHPCode”
Step7
Click on “add.php” and it will show the
following:
A PHP script can be placed anywhere in the
document.
A PHP script starts with <?php and ends with
?>
The default file extension for PHP files is
".php".
A PHP file normally contains HTML tags, and
some PHP scripting code.
Below, we have an example of a simple PHP file,
with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!"
on a web page:
Code
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
My first PHP page
Hello World!
A comment in PHP code is a line that is not
read/executed as part of the program.
Its only purpose is to be read by someone
who is looking at the code.
Remind yourself of what you did.
PHP supports several ways of commenting.
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
In PHP, all keywords (e.g. if, else, while, echo,
etc.), classes, functions, and user-defined
functions are NOT case sensitive.
In the example below, all three echo
statements below are legal (and equal):
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Hello World!
Hello World!
Hello World!
All variable names are case-sensitive.
In the example below, only the first statement
will display the value of the $color variable
(this is because $color, $COLOR, and $coLOR
are treated as three different variables):
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
My car is red
My house is // it does not show color name
My boat is // it does not show color name
Variables can store data of different types, and
different data types can do different things.
PHP supports the following data types:
String
Integer
Float (double)
Boolean
Array
Object
NULL
A string is a sequence of characters, like "Hello
world!".
A string can be any text inside quotes. You can
use single or double quotes:
PHP Code
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hello world!
Hello world!
An integer is a whole number (without
decimals). It is a number between -
2,147,483,648 and +2,147,483,647.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
In the following example $x is an integer. The
PHP var_dump() function returns the data
type and value:
<?php
$x = 598;
var_dump($x);
?>
Output
int(598)
A float (floating point number) is a number
with a decimal point or a number in
exponential form.
In the following example $x is a float. The
PHP var_dump() function returns the data
type and value:
<?php
$x = 10.365;
var_dump($x);
?>
<?php
$x = 10.365;
var_dump($x);
?>
Output :
float(10.365)
A Boolean represents two possible states:
TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing
An array stores multiple values in one single
variable.
In the following example $cars is an array.
The PHP var_dump() function returns the data
type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
array(3) { [0]=> string(5) "Volvo" [1]=>
string(3) "BMW" [2]=> string(6) "Toyota" }
Null is a special data type which can have
only one value: NULL.
A variable of data type NULL is a variable that
has no value assigned to it.
Note: If a variable is created without a value,
it is automatically assigned a value of NULL.
Variables can also be emptied by setting the
value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
An object is a data type which stores data and
information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For
this, we use the class keyword. A class is a
structure that can contain properties and
methods:
<?php
class Car {
function Car() {
$this->model = "VW";
}}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
PHP Variables
Variables are "containers" for storing
information.
How to Declare PHP Variables
In PHP, a variable starts with the $ sign,
followed by the name of the variable:
Examples :
$txt = "Hello world!";
$x = 5;
$y = 10.5;
A variable can have a short name (like x and
y) or a more descriptive name (age, carname,
total_volume.
A variable starts with the $ sign, followed by
the name of the variable
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alphanumeric characters and underscores (A-z, 0-
9, and _ )
Variable names are case-sensitive ($age and
$AGE are two different variables)
Note : Remember that PHP variable names are
case-sensitive!
The PHP echo statement is often used to
output data to the screen.
The following example will show how to
output text and a variable:
<?php
$txt = “Pakistan";
echo "I love $txt!";
?>
Output will be
I love Pakistan!
Another example for variable addition:
Code :
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP automatically converts the variable to the
correct data type, depending on its value.
In other languages such as C, C++, and Java,
the programmer must declare the name and
type of the variable before using it.
PHP Variables Scope
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
A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function:
Example:
<?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>";
?>
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that
function:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an
error
echo "<p>Variable x outside function is: $x</p>";
?>
Variable x inside function is: 5
Variable x outside function is:
The global keyword is used to access a global
variable from within a function.
To do this, use the global keyword before the
variables (inside the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Normally, when a function is
completed/executed, all of its variables are
deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a
further job.
To do this, use the static keyword when you
first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
0 1 2
Note : Then, each time the function is called,
that variable will still have the information it
contained from the last time the function was
called.
The real power of PHP comes from its functions;
it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create
our own functions.
A function is a block of statements that can be
used repeatedly in a program.
A function will not execute immediately when a
page loads.
A function will be executed by a call to the
function.
A user defined function declaration starts with the
word "function":
Syntax
function functionName() {
code to be executed;
}
A function name can start with a letter or
underscore (not a number).
Give the function a name that reflects what
the function does.
Function names are NOT case-sensitive.
<?php
function writeMsg() {
echo “Welcome to PHP Page!";
}
writeMsg(); // call the function
?>
OutPut
Welcome to PHP Page
Information can be passed to functions
through arguments. An argument is just like
a variable.
Arguments are specified after the function
name, inside the parentheses. You can add as
many arguments as you want, just separate
them with a comma.
The following example has a function with one
argument ($fname). When the familyName()
function is called, we also pass along a name
(e.g.Ali), and the name is used inside the
function, which outputs several different first
names, but an equal last name:
<?php
function familyName($fname) {
echo "$fname Ahmed.<br>";
}
familyName(“Ali");
familyName(“Usman");
familyName(“Hafeez");
?>
Output:
Ali Ahmed
Usman Ahmed
Hafeez Ahmed
<?php
function familyName($fname, $year) {
echo "$fname Ahmed. Born in $year <br>";
}
familyName(“Ali", "1975");
familyName(“Usman", "1978");
familyName(“Hafeez", "1983");
?>
Output:
Ali Ahmed. Born in 1975
Usman Ahmed. Born in 1978
Hafeez Ahmed. Born in 1983
The following example shows how to use a
default parameter. If we call the function
setHeight() without arguments it takes the
default value as argument:
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
?>
Output :
The height is : 350
The height is : 50
The height is : 135
To let a function return a value, use the
return statement:
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
?>
Output:
5 + 10 = 15
7 + 13 = 20
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.
In PHP we have the following conditional
statements:
if statement
if...else statement
if...elseif....else statement
switch statement
The if statement is used to execute some
code only if a specified condition isis true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good
day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Output :
Have a good day!
Use the if....else statement to execute some
code if a condition isis true and another code if
the condition isis false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good
day!" if the current time is less than 20, and
"Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Use the if....elseif...else statement to specify a
new condition to test, if the first condition isis
false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good
morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output :
The hour (of the server) is 03, and will give
the following message:
Have a good morning!
The switch statement is used to perform
different actions based on different
conditions.
Use the switch statement to select one of
many blocks of code to be executed.
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;
}
Ø How switch statement 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.
<?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":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Output:
Your favorite color is red!
In computer programming, a loop is a
sequence of instruction s that is continually
repeated until a certain condition is reached.
PHP Loops :
In PHP, we have the following looping
statements:
while
do...while
for
foreach
The while loop executes a block of code as
long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The do...while loop will always execute the
block of code once, it will then check the
condition, and repeat the loop while the
specified condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x
= 1). Then, the do while loop will write some
output, and then increment the variable $x with 1.
Then the condition is checked (is $x less than, or
equal to 5?), and the loop will continue to run as
long as $x is less than, or equal to 5:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The example below sets the $x variable to 6,
then it runs the loop, and then the condition
isis checked.
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
Output
The number is: 6
The for loop is used when you know in
advance how many times the script should
run.
Syntax
for (init counter; test counter; increment
counter) {
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop
iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop
ends.
increment counter: Increases the loop counter
value
The example below displays the numbers
from 0 to 10:
<?php
for ($x = 0; $x <= 5; $x++) {
echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The foreach loop works only on arrays, and is
used to loop through each key/value pair in
an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
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):
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Output:
red
green
blue
yellow
An array stores multiple values in one single
variable.
Example:
<?php
$cars = array(“Honda Civic", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
Output:
I like Honda Civic, BMW and Toyota
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 = “Honda Civic";
$cars2 = "BMW";
$cars3 = "Toyota";
An array can hold many values under a single
name, and you can access the values by
referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create
an array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing
one or more arrays
There are two ways to create indexed arrays:
The index can be assigned automatically
(index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed
array named $cars, assigns three elements to
it, and then prints a text containing the array
values:
<?php
$cars = array(“Swift", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and "
. $cars[2] . ".";
?>
I like Swift, BMW and Toyota.
The count() Function:
The count() function is used to return the
length (the number of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output:
3
To loop through and print all the values of an
indexed array, you could use a for loop, like this:
<?php
$cars = array(“Swift", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Swift
BMW
Toyota
Associative arrays are arrays that use named
keys that you assign to them.
There are two ways to create an associative
array:
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
OR
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output:
Peter is 35 years old.
To loop through and print all the values of an
associative array, you could use a foreach loop, like
this:
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.
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
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.
The dimension of an array indicates the
number of indices you need to select an
element. For a two dimensional array you
need two indices to select an element
For a three dimensional array you need three
indices to select an element
Name Stock Sold
Volvo 22 18
BMW 15 13
Swift 5 2
Land Rover 17 15
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Swift",5,2),
array("Land Rover",17,15)
);
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
A string is a sequence of characters, like "Hello
world!".
PHP String Functions:
Get The Length of a String
The PHP strlen() function returns the length of a
string.
The example below returns the length of the string
"Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Output:
12
Count The Number of Words in a String
The PHP str_word_count() function counts the
number of words in a string:
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
The output of the code above will be: 2.
Reverse a String
The PHP strrev() function reverses a string:
<?php
echo strrev("Hello world!");
// outputs !dlrow olleH
?>
Search For a Specific Text Within a String
The PHP strpos() function searches for a specific
text within a string.
If a match is found, the function returns the
character position of the first match. If no match is
found, it will return FALSE.
The example below searches for the text "world"
in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The output of the code above will be: 6.
Note: The first character position in a string is 0
(not 1).
Replace Text Within a String
The PHP str_replace() function replaces some
characters with some other characters in a string.
The example below replaces the text "world" with
"Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!");
// outputs Hello Dolly!
?>
Basic Concepts of OOP
Object-Oriented Programming (OOP) is a type
of programming added to php5 that makes
building complex, modular and reusable web
applications that much easier.
There are some basic concepts about OOP
Which are as follows :
Class
Object
Member Variable
Member function
Inheritance
Parent class.
Child Class.
Polymorphism
Overloading
Data Abstraction
Encapsulation
Constructor
Destructor
Class :This is a programmer-defined data type,
which includes local functions as well as local
data. You can think of a class as a template for
making many instances of the same kind (or
class) of object.
Object An individual instance of the data
structure defined by a class. You define a class
once and then make many objects that belong
to it. Objects are also known as instance.
Member Variable : These are the variables
defined inside a class. This data will be
invisible to the outside of the class and can
be accessed via member functions. These
variables are called attribute of the object
once an object is created.
Member function : These are the function
defined inside a class and are used to access
object data.
Inheritance : When a class is defined by
inheriting existing function of a parent class
then it is called inheritance. Here child class
will inherit all or few member functions and
variables of a parent class.
Parent class : A class that is inherited from by
another class. This is also called a base class
or super class.
Child Class: A class that inherits from another
class. This is also called a subclass or derived
class
Polymorphism: This is an object oriented
concept where same function can be used for
different purposes. For example function
name will remain same but it make take
different number of arguments and can do
different task.
Overloading : a type of polymorphism in
which some or all of operators have different
implementations depending on the types of
their arguments. Similarly functions can also
be overloaded with different implementation.
Data Abstraction : Any representation of data in
which the implementation details are hidden
(abstracted).
Encapsulation : refers to a concept where we
encapsulate all the data and member functions
together to form an object.
Constructor : refers to a special type of function
which will be called automatically whenever there
is an object formation from a class.
Destructor : refers to a special type of function
which will be called automatically whenever an
object is deleted or goes out of scope.
First thing we need to do is create two PHP
pages:
index.php
class_lib.php
OOP is all about creating modular code, so our
object oriented PHP code will be
contained in dedicated files that we will then
insert into our normal PHP page using
php 'includes'. In this case all our OO PHP code
will be in the PHP file:
class_lib.php
You define your own class by starting with
the keyword 'class' followed by the name
you want to give your new class.
<?php
class person {
}
One of the big differences between functions and
classes is that a class contains both data
(variables) and functions that form a package
called an: 'object'. When you create a
variable inside a class, it is called a 'property'.
<?php
class person {
var $name;
}
Note: The data/variables inside a class (var
$name;) are called 'properties'.
In the same way that variables get a different
name when created inside a class(they are
called: properties,) functions also referred to
by a different name when created inside a
class they are called 'methods'.
A classes' methods are used to manipulate
its' own data / properties.
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name; }
}
We have created two interesting
functions/methods:
get_name() and set_name().
STEP 6: The '$this' variable
The $this is a built-in variable (built into all
objects) which points to the current
object. Or in other words, $this is a special
self-referencing variable.
You use $this to access properties and to call
other methods of the current class.
function get_name() {
return $this->name;
}
You would never create your PHP classes
directly inside your main php pages.
Instead, it is always best practice to create
separate php pages that only contain
your classes.
Then you would access your php
objects/classes by including them in your
main php pages with either a php 'include' or
'require'.
<html>
<head>
<title>OOP in PHP</title>
<?php include("class_lib.php"); ?>
</head>
<body>
</body>
</html>
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
?>
</body>
</html>
The variable $stefan becomes a
handle/reference to our newly created person
object.
STEP 9: The 'new' keyword
To create an object out of a class, you need
to use the 'new' keyword.
When creating/instantiating a class, you can
optionally add brackets to the class name.
As we did in the example below. To be clear,
you can see in the code below how we can
create multiple objects from the same class.
<body>
<?php
$stefan = new person();
$jimmy = new person();
?>
</body>
We have created our two separate 'person'
objects, we can set their properties using the
methods (the setters) we created.
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
}
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name(“ Jimmy Nick");
?>
</body>
</html>
<?php include("class_lib.php"); ?>
</head>
<body>
<?php$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
echo "Stefan's full name: " . $stefan->get_name();
echo "Nick's full name: " . $jimmy->get_name();
?>
</body>
</html>
You don't have to use methods to access
objects properties; you can directly get to
them using the arrow operator (->) and the
name of the variable.
See Example on next slide
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
echo "Stefan's full name: " . $stefan->name;
?>
</body>
</html>
All objects can have a special built-in method
called a 'constructor'. Constructors allow you
to initialize your object's properties.
The 'construct' method starts with two
underscores (__) and the word 'construct'.
You 'feed' the constructor method by
providing a list of arguments (like a function)
after the class name.
<?php
2. class person {
3. var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function set_name($new_name) {
$this->name = $new_name;
}
Now that we've created a constructor method, we
can provide a value for the $name property when
we create our person objects.
For example: $stefan = new person("Stefan
John");
<?php
$stefan = new person("Stefan Mischook");
echo "Stefan's full name: " $stefan->get_name();
?>
</body>
</html>
Note: This saves us from having to call the set_name()
method reducing the amount of code.
One of the fundamental principles in OOP is
'encapsulation'. The idea is that you create
cleaner better code, if you restrict access to the
data structures (properties) in your objects.
You restrict access to class properties using
something called 'access modifiers'.
There are 3 access modifiers:
• public
• private
• protected
Public is the default modifier.
<?php
class person {
var $name;
public $height;
protected $social_insurance;
private $pinn_number;
}
>
Note: When you declare a property with the
'var' keyword, it is considered 'public
When you declare a property as 'private', only
the same class can access the property.
When a property is declared 'protected', only
the same class and classes derived from that
class can access the property - this has to do
with inheritance …more on that later.
Properties declared as 'public' have no access
restrictions, meaning anyone can access
them.
Like properties, you can control access to
methods using one of the three access
modifiers:
public
protected
private
Doing this allows you to efficiently reuse the
code found in your base class.
<?php
// 'extends' is the keyword that enables
inheritance
class employee extends person {
function __construct($employee_name) {
}
}
?>
Sometimes (when using inheritance,) you may
need to change how a method works from
the base class.
For example, let's say set_name() method in
the 'employee' class, had to do something
different than what it does in the 'person'
class.
Using :: allows you to specifically name the class
where you want PHP to search for
a method - 'person::set_name()' tells PHP to search
for set_name() in the 'person‘ class.
<?php
/* explicitly adding class properties are optional -
but is good practice */
class person {
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function get_name() {
return $this->name;
}
// protected methods and properties restrict
//access to those elements
protected function set_name($new_name) {
if (name != "Jimmy Two Guns") {
$this->name = strtoupper($new_name); }
}
}
protected function set_name($new_name) {
if ($new_name == "Stefan Lamp") {
$this->name = $new_name;
}
else if($new_name == "Johnny Fingers") {
parent::set_name($new_name);
}
}
function __construct($employee_name) {
$this->set_name($employee_name); }
}
?>
One of the cool features of PHP is the huge
collection of built-in functions it provides.
You can call these functions anywhere in your
scripts without defining.
$amount = 537.1267;2.
$newAmount=round($amount, 2);
// output will be 537.13
Working with date() function
Date() is a built-in php function for showing
date. we can pass it many different
values/arguments.
Here some examples: */
echo "<p>". date("D") ."</p>";
//Day name in three letters => Tue
echo "<p>". date("M") ."</p>";
//Month name in three letters => Dec
/* Here some examples of functions to check
a variable data type: */
is_int($variable)
//check if is INTEGER, returns a Boolean (true/false)
is_float($variable)
//check if is FLOAT, returns a Boolean (true/false)
is_string($variable)
//check if is STRING, returns a Boolean (true/false)
/* isset() allows you to check if a variable has
been previously set: */
isset($variable)
// returns a Boolean (true/false)
/* Here some examples of functions to use to
handle form data: */
strval(intval($variable))
//STRVAL gets the string value of a variable
strval(floatval($variable))
/*INTVAL and FLOATVAL get the integer/float
value of a var */
addslashes($variable)
// Escape single quote with a back slash
stripslashes($variable)
// Escape back slash from string
The Standard PHP Library (SPL) is where PHP
5's object-oriented capabilities truly shine. It
improves the language in five key ways:
iterators, exceptions, array overloading, XML,
and file and data handling.. Additionally, it
offers advanced functionality for autoloading classes and interfaces.
class_implements — Return the interfaces
which are implemented by the given class or
interface
class_parents — Return the parent classes of
the given class
iterator_apply — Call a function for every
element in an iterator
iterator_count — Count the elements in an
iterator
iterator_to_array — Copy the iterator into an
array
When you work with an application, you open
it, do some changes, and then you close it.
This is much like a Session. The computer
knows who you are. It knows when you start
the application and when you end. But on the
internet there is one problem: the web server
does not know who you are or what you do,
because the HTTP address doesn't maintain
state.
Session variables solve this problem by
storing user information to be used across
multiple pages (e.g. username, favorite color,
etc). By default, session variables last until
the user closes the browser.
So Session variables hold information about
one single user, and are available to all pages
in one application
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Example :
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html> // output : Session variables are set.
Next, we create another page called
"demo_session2.php". From this page, we will
access the session information we set on the
first page ("demo_session1.php").
Notice that session variables are not passed
individually to each new page, instead they
are retrieved from the session we open at the
beginning of each page (session_start()).
Also notice that all session variable values are
stored in the global $_SESSION variable:
<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Output :
Favorite color is green.
Favorite animal is cat.
To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html> //output : Array ( [favcolor] => yellow [favanimal] => cat )
To remove all global session variables and destroy the
session, use session_unset() and session_destroy():
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
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
A cookie is created with the setcookie()
function.
Syntax
setcookie(name, value, expire, path, domain,
secure, httponly);
Only the name parameter is required. All
other parameters are optional.
The given example creates a cookie named
"user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/"
means that the cookie is available in entire
website (otherwise, select the directory you
prefer).
We then retrieve the value of the cookie "user"
(using the global variable $_COOKIE). We also
use the isset() function to find out if the
cookie is set:
<?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];
}
?>
</body>
</html.
Note: The setcookie() function must appear BEFORE the <html> tag.
Cookie named 'user' is not set!
Note: You might have to reload the page to
see the value of the cookie
To modify a cookie, just set (again) the cookie using the setcookie()
function:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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];
}
?>
</body>
</html>
Output :
Cookie 'user' is set!
Value is: John DoeNote: You might have to
reload the page to see the new value of the
cookie.
To delete a cookie, use the setcookie() function with an
expiration date in the past:
<html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Output: Cookie 'user' is deleted.
The following example creates a small script that checks whether
cookies are enabled. First, try to create a test cookie with the
setcookie() function, then count the $_COOKIE array variable:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
output : Cookies are enabled
Exceptions are used to change the normal flow of
a script if a specified error occurs.
This is what normally happens when an
exception is triggered:
The current code state is saved.
The code execution will switch to a predefined
(custom) exception handler function.
Depending on the situation, the handler may
then resume the execution from the saved code
state, terminate the script execution or continue
the script from a different location in the code.
When an exception is thrown, the code
following it will not be executed, and PHP will
try to find the matching "catch" block.
If an exception is not caught, a fatal error will
be issued with an "Uncaught Exception"
message.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or
below");
}
return true;
}
//trigger exception
checkNum(2);
?>
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in
C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in
C:\webfolder\test.php on line 6
To avoid the error from the example above, we
need to create the proper code to handle an
exception.
Proper exception code should include:
Try - A function using an exception should be in
a "try" block. If the exception does not trigger,
the code will continue as normal. However if the
exception triggers, an exception is "thrown"
Throw - This is how you trigger an exception.
Each "throw" must have at least one "catch"
Catch - A "catch" block retrieves an exception
and creates an object containing the exception
information
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
The code above throws an exception and
catches it:
The checkNum() function is created. It checks
if a number is greater than 1. If it is, an
exception is thrown
The checkNum() function is called in a "try"
block
The exception within the checkNum()
function is thrown
The "catch" block retrieves the exception and
creates an object ($e) containing the
exception information
The error message from the exception is
echoed by calling $e->getMessage() from the
exception object
However, one way to get around the "every
throw must have a catch" rule is to set a top
level exception handler to handle errors that
slip through.
• Open the XAMPP Control Panel.
• To turn Apache and mySQL on/off, simply click the respective start/stop
buttons for each component.
• The buttons will change state depending on the status of the component.
• Open your browser and go to http://localhost/.
• XAMPP welcome screen
phpMyAdmin
• Database is an organized collection of related data. For example, hospital
database, school database etc..
• Relation databases
• A relational database (RDB) is a collective set of multiple data sets
organized by tables, records and columns.
• Each table is known as a relation.
• RDBs establish a well-defined relationship between database tables.
• DBMS
• A database management system (DBMS) is system software for creating
and managing databases.
• It provides users and programmers with a systematic way to create,
retrieve, update and manage data.
1. Table Columns
Rows
3. Primary Key
• It is a special relational database table column (or combination of
columns) designated to uniquely identify all table records.
• It must contain a unique value for each row of data.
• It cannot contain null values.
4. Foreign Key
• It is a column (or columns) that references a column (most often the
primary key) of another table.
• It ensures referential integrity of the data.
5. Referential Integrity
• It requires every value of one attribute of a relation to exist as a value of
another attribute in a different relation.
• mySQL is an open source Relational Database Management System
that uses Structured Query Language (SQL).
• It is very fast, reliable, scalable, and easy to use.
• It works on many operating systems and with many languages
including PHP, PERL, C, C++, JAVA, etc.
• It is very friendly to PHP, the most appreciated language for web
development.
• It supports large databases.
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
die() function
• The die() function prints a message and exits the current script.
• This function is an alias of the exit() function.
mysql_error () function
• Returns the text of the error message from previous MySQL operation
mysql_close() function
• closes the non-persistent connection to the MySQL server
• Open non-persistent MySQL connections and result sets are automatically
destroyed when a PHP script finishes its execution
• PHP uses mysql_query function to create or delete a MySQL database.
This function takes two parameters and returns TRUE on success or
FALSE on failure.
• Syntax:
• bool mysql_query( sql, connection );
• Parameters
• Description
• Sql
• Required - SQL query to create or delete a MySQL database
• Connection
• Optional - if not specified, then last opened connection by mysql_connect
will be used.
• <html>
• <head>
• <title>Creating MySQL Database</title>
• </head>
• <body>
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn )
• {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully<br />';
• $sql = 'CREATE DATABASE TUTORIALS';
• $retval = mysql_query( $sql, $conn );
• if(! $retval )
• {
• die('Could not create database: ' . mysql_error());
• }
• echo "Database TUTORIALS created successfully\n";
• mysql_close($conn);
• ?>
• </body>
• </html>
• CHAR(size)
• It holds a fixed length string specified in parenthesis.
• It can store up to 255 characters
• It can contain letters, numbers, and special characters.
• VARCHAR(size)
• It holds a variable length string, specified in parenthesis.
• It can store up to 255 characters.
• It can contain letters, numbers, and special characters.
• AutoNumber
• It automatically gives each record its own number, usually starting at 1
• INT(size)
• Range is -2147483648 to 2147483647.
• 0 to 4294967295 UNSIGNED.
• The maximum number of digits may be specified in parenthesis
• FLOAT(size,d)
• A small number with a floating decimal point.
• The maximum number of digits may be specified in the size parameter.
• The maximum number of digits to the right of the decimal point is specified in
the d parameter
• DATE()
• A date.
• Format: YYYY-MM-DD
• The supported range is from '1000-01-01' to '9999-12-31'
• DATETIME()
• A date and time combination.
• Format: YYYY-MM-DD HH:MI:SS
• TIME()
• A time. Format:
• HH:MI:SS
• The supported range is from '-838:59:59' to '838:59:59'
• YEAR()
• A year in two-digit(15) or four-digit format(2015).
• optional attributes for each column:
• NOT NULL
• Each row must contain a value for that column
• null values are not allowed
• firstname VARCHAR(30) NOT NULL;
• DEFAULT value
• Set a default value that is added when no other value is passed
• Gender VARCHAR(20) DEFAULT “Female”
• UNSIGNED
• Used for number types
• Limits the stored data to positive numbers and zero
• Salary INT(6) UNSIGNED NOT NULL
• AUTO INCREMENT
• mySQL automatically increases the value of the field by 1 each time a
new record is added
• id INT(6) UNSIGNED AUTO_INCREMENT;
• PRIMARY KEY
• Used to uniquely identify the rows in a table.
• The column with PRIMARY KEY setting is often an ID number and is
often used with AUTO_INCREMENT.
• id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
• FOREIGN KEY
• It points to a PRIMARY KEY in another table.
• FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
The table creation command requires:
• Name of the table
• Names of fields
• Definitions for each field
Syntax:
• Here is generic SQL syntax to create a MySQL table:
CREATE TABLE table_name (column_name column_type);
• CREATE TABLE tutorials_tbl(
• tutorial_id INT NOT NULL AUTO_INCREMENT,
• tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
• submission_date DATE,
• PRIMARY KEY ( tutorial_id )
• Select
• Insert
• Update
• Delete
• INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
• SELECT column_name(s) FROM table_name
• SELECT * FROM table_name
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
• DELETE FROM table_name
WHERE some_column = some_value
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
• UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
• The main functionality of the PhpMyAdmin tool is to manage your
databases.
• Click on the Databases link and create the database or Pick the preferred
database which you want to manage and click on its name.
• Create the new Table
• CREATE TABLE `employee` ( `id` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT
NULL, `job_title` varchar(100) DEFAULT NULL, `salary` double DEFAULT
NULL, `notes` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT
CHARSET=utf8;
• You will see the fields' names, their types, collations, attributes, additional
extra information, the default values and whether the fields' values can be
NULL. You can browse for distinct values by clicking on the corresponding
action icon. Also, you can edit a field's structure or delete a field. You can
define different indexes: Primary, Unique, Index and Fulltext.
• In the Indexes area you will find the indexes assigned for the table and the
fields for which they are set. You can edit and delete them.
• Only the tables with existing records can be browsed. Once you click on the
Browse icon a new window with the records list will be opened.
• By clicking on the Pen icon you can edit the chosen record.
• You will see the record structure and you can alter the values of the
records.
Using the Insert action you can insert records in your database table.
INSERT INTO `employee` (`first_name`, `last_name`, `job_title`, `salary`)
VALUES (‘Ali', ‘Imran', 'Software Engineer', 5500), (‘khalid', ‘Mehmood',
'Software Architect', 7200), (‘Danish', ‘Husnain', 'Database Administrator',
6000), (‘Muhammad', ‘Aryan', 'Database Administrator', 6800), (‘Hameed',
‘Gul', 'Software Engineer', 4750), (‘Sara', ‘Ali', 'Software Engineer', 5100),
(‘Hina', ‘Waseem', 'Project Manager', 8500), (‘Iqra', ‘Husnain', 'Software
Architect', 8000);
• Once you fill in the corresponding values click on the Go button and the
new record will be inserted.
• Relational databases provide lots of options and power for indices and
keys:
• a index on 1 / several columns can dramatically improve performance
• you can designate an index as unique (duplicates are rejected at runtime)
• the Primary Key is the main unique index.
• Auto_Increment Primary Keys
• Many database designers elect to define a column (often called Id) as a
system-computed AUTO_INCREMENT. This is also called a surrogate
key (as distinct from a natural key).
• This can simplify your database design, as shown for employee, below:
• You define a Relationship by defining a Foreign Key, wherein the child
contains the Primary Key of the Parent.
• To define a Foreign Key Relationship:
• Create an index on the Child Column(s) that comprise the Foreign Key
• Create the Relationship.Note there is substantial power in the Cascade
rules.
• Create the Relationship by selecting the Child Table > Structure > Relation
View:
• In our example, the employee_education (child) contains a field
(education_id) that matches the Primary Key of the Employee (parent),
the Id.
• CREATE TABLE `employee_education` (
• `employee_id` int NOT NULL,
• `education_id` tinyint NOT NULL
• ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
• INSERT INTO `employee_education` (`employee_id`, `education_id`)
VALUES
• (1, 1),
• (2, 1),
• (3, 2),
• (3, 3);
CASCADE
• Whenever rows in the master (referenced) table are deleted (resp.
updated), the respective rows of the child (referencing) table with a
matching foreign key column will get deleted as well. This is called a
cascade delete.
RESTRICT
• A value cannot be updated or deleted when a row exists in a foreign key
table that references the value in the referenced table. Similarly, a row
cannot be deleted as long as there is a reference to it from a foreign key
table.
NO ACTION
• NO ACTION and RESTRICT are very much alike. The main difference
between NO ACTION and RESTRICT is that with NO ACTION the
referential integrity check is done after trying to alter the table. RESTRICT
does the check before trying to execute the UPDATE or DELETE
statement. Both referential actions act the same if the referential integrity
check fails: the UPDATE or DELETE statement will result in an error.
SET NULL
• The foreign key values in the referencing row are set to NULL when the
referenced row is updated or deleted. This is only possible if the respective
columns in the referencing table are nullable. Due to the semantics of
NULL, a referencing row with NULLs in the foreign key columns does not
require a referenced row.
• The WHERE clause is used to filter records.
Syntax
• SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
• = (Equal)
• <>(Not equal (Also written as !=))
• > (Greater than)
• < (Less than)
• >= (Greater than or equal)
• <= (Less than or equal)
• BETWEEN
• Between an inclusive range
• Equal
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’;
• Greater
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id>10";
• Less then
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id<10";
• Between
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id
between 5 AND 10“;
• AND
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ AND lastname=‘Ehsaan’";
• OR
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ OR firstname=‘Pasha’";
• Arrange the results in ascending or descending order.
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ OR firstname=‘Pasha’ ORDERED BY firstname DESC”;
• JOIN clause is used to combine rows from two or more tables, based on a
common field between them.
• Types of joins
• Inner join
• Left join
• Right join
• Inner joins let us select rows that have same value in both tables for
specified columns thereby returns matching rows. We specify the first table
after FROM as in normal SELECT statements and the second table is
specified after INNER JOIN.
• Using ON clause we can specify the columns that should have matching
values.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
For example
• $sql = “SELECT e.first_name, e.last_name, u.user_type, u.username
FROM `employee` INNER JOIN `user` ON e.id = u.employee_id ";
• Left joins let you select all the rows from first table (left table) for specified
relationship and fetch only the matching ones from second table (right
table)
• SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
• $sql = " SELECT e.first_name, e.last_name, u.user_type, u.username
FROM `employee` LEFT JOIN `user` ON e.id = u.employee_id ";
• Right joins work opposite to left joins. That is, priority is given to right table
and fetches all the rows from right table for given relationship.
• SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
• $sql = " SELECT e.first_name, e.last_name, u.user_type,
u.usernameFROM `employee` RIGHT JOIN `user` ON u.employee_id =
e.id ";
• View is a virtual table based on the result-set of an SQL statement
• It contains rows and columns, just like a real table.
• The fields in a view are fields from one or more real tables in the database.
CREATE VIEW SYNTAX
Create view view_name AS
Select column_name(s)
From table_name
Where condition
Example:
create view employee_1 AS select first_name,last_name from employee
where id = 1
Step1:Open your XAMPP control panel and click admin button to get
into PHPMyAdmin window.
Step2: Before connecting MYSQL with PHP we need to create a
database first. Click on database tab and inside the database name
field type a name of VUDATABASE and go with the default setting
which is collation and hit create.
Step3: Open a notepad /dreamweaver and write the PHP script as
shown in snapshot to connect with MYSQL.
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to
the server:
Code:
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “xamp")
or die();
mysql_select_db (“VUDATABASE", $conn) or die( );
echo (" Database connected successfully");
?>
Close the Connection
The connection will be closed automatically when the script ends. To
close the connection before, use the following:
$conn->close();
Display on web site “Connected database successfully”
Step1:Open your XAMPP control panel and click admin button to get
into XAMPP for windows.
Step2: Click on security tab
Step3 Inside the security window field type the password and click on
password changing tab
Step 4:open the phpMyAdmin window and enter the username “root”
and password “xamp”for authentication
There are two ways the browser client can send information to the
web server.
1. The GET Method
2. The POST Method
We see a lot of forms while surfing the internet. Like creating an
email account or subscribe to a newsletter by name/email etc. When
we fill the forms with data, the PHP provides methods to receive it
just like other web based languages.
The GET PHP method sends information by appending variables to the end
of URL. The page and information is separated by a ‘?’ (question mark)
character. You can use PHP Get method ($_GET) to catch the sent data.
The URL would look like this in address bar after Submitting information by
using the Get method:
For example
http://www.yourdomain.com/index.htm?name=myname&age=30&location=
Pakistan
Following example shows using the PHP GET method with form’s get method.
PHP code:
<?php
if( $_GET["yourname"] || $_GET["yourage"] )
{
echo "Welcome ". $_GET['yourname']. "<br />";
echo "Your age is ". $_GET['yourage']. " years.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Your Name: <input type="text" name="yourname" />
Your Age: <input type="text" name="yourage" />
<input type="submit" />
</form>
</body>
</html>
PHP CODE OUTPUT
Your Name: Your Age: submit
After entering the name and age in the above example, when you click
the submit button, it will come back to the same page and display your
name and age. If you look at the address bar, you will see the following:
For example, if you entered the name as ‘ALI’ and age ’30’ while your
domain is “localhost” and page name is index.php then this is how the
address bar would look:
http://localhost/index.php?yourname=ALI&yourage=30
Following are the points to be noticed as using the Get in above
example:
In the HTML form, the method= ”GET” is used.
When receiving information at the server side, you have to use this:
PHP $_GET to get variable names sent by forms.
e.g. $_GET[‘yourname’]. You may assign this to a variable and save it to
database e.g. $name=$_GET[‘yourname’];
The HTML form data will be visible in the address bar as using the Get
method. Where “?” is used to separate from domain and variables are
separated by the “&” characters.
The amount of data that can be sent is limited in GET method. It is
about 2000 characters limit.
The GET method cannot send binary data.
As variables are visible in the address bar, this is visible to anyone
so considered as un-secure. This may be helpful in case you want to
offer bookmarking your site with non-sensitive data.
Get should not be used for sensitive information like passwords.
PHP $_GET is used to retrieve sent data along with using the form’s
get method.
The information sent by using the POST PHP method is not visible to
the users. The data sent by using post method of forms is received by
PHP POST method as shown below.
Following example shows using the PHP GET method with form’s get method.
PHP code:
<?php
if( $_POST["yourname"] || $_POST["yourage"] )
{
echo "Welcome ". $_POST['yourname']. "<br />";
echo "You age is ". $_POST['yourage']. " years.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Your Name: <input type="text" name="yourname" />
Your Age: <input type="text" name="yourage" />
<input type="submit" />
</form>
</body>
</html>
PHP CODE OUTPUT
Your Name: Your Age: submit
After entering the name and age in the above page, when you click
the submit button, it will come back to the same page and display
your name and age. You can see, the address bars will show just
the .phpfile name.
Following things should be noticed in the above example:
In the HTML form, the method=”POST” is used.
We used PHP $_POST to get the variable names sent by the form.
e.g. $_POST[‘yourname’].
Form variables will not be visible in the address bar, unlike the GET
method.
The amount of data that can be sent is not limited in the POST
method.
POST method can send binary data. So this method is used to
upload files like images, word document, pdfs, or other formats.
POST should be used for sensitive information like passwords etc.
Your users won’t be able to bookmark the page with submitted
information to be used in next visits as information is not visible.
You have to use the PHP Post method ($_POST) to retrieve the
information sent by web forms.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>form interface</title>
</head>
<body>
<form action="form.php"method="post">
name: <input type="text" name = "fname"><br>
age: <input type="text" name = "age"><br>
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form submission</title>
</head>
<body>Web form <br>
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “1234")
or die();
mysql_select_db ("vutest", $conn) or die( );
echo (" DB connected successfully");
$sql="INSERT INTO employee(NAME, AGE)
VALUES
('$_POST[fname]','$_POST[age]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "Record added successfully";
mysql_close($conn)
?>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form submission</title>
</head>
<body>Web form <br>
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “1234")
or die();
mysql_select_db ("vutest", $conn) or die( );
echo (" DB connected successfully");
$sql = 'SELECT ID, NAME, Age
FROM employee';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Id :{$row['ID']} <br> ".
"Name: {$row['NAME']} <br> ".
"AGE: {$row['Age']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Web Security, also known as “Cyber security” involves
protecting that information by preventing, detecting, and
responding to attacks
Web application security is the process of securing
confidential data stored online from unauthorized access
and modification.
Web browser (front end)
Web application (back end)
Prevent unauthorized users from accessing
sensitive data
◦ Authentication: identifying users to determine if they are
one of the authorized ones
◦ Access control: identifying which resources need
protection and who should have access to them
Prevent attackers from stealing data from network
during transmission
Web application security aims to address and fulfill the four conditions of security
Confidentiality: States that the sensitive data stored in the Web application
should not be exposed under any circumstances.
Integrity: States that the data contained in the Web application is consistent
and is not modified by an unauthorized user.
Availability: States that the Web application should be accessible to the
authentic user within a specified period of time depending on the request.
Nonrepudiation: States that the authentic user cannot deny modifying the data
contained in the Web application and that the Web application can prove its
identity to the authentic user.
The process of security analysis runs parallel with Web application
development. The group of programmers and developers who are responsible
for code development are also responsible for the execution of various
strategies, post-risk analysis, mitigation and monitoring.
There are two general approaches to the declarative
security for the Web application framework:
BASIC Authentication
Form-based Authentication
• By using declarative security, all you need to do is to put
the protected data in a directory
• The server will pop up a standard authentication window
asking for username & password upon user’s requests to
access restricted resources (specified directory or files).
Web server collects user identification information
via a customized login page, e.g.
• The Internet is a worldwide collection of computer networks
connecting academic, governmental, commercial, and
organizational sites.
• It provides access to communication services and
information resources to millions of users around the globe.
• Internet services include:
• direct communication (e-mail, chat)
• online conferencing (Usenet News, e-mail discussion
lists)
• remote login and file transfer (telnet, ftp)
• and many other valuable tools and resources
→ The Internet and the WWW are not synonyms
• WWW also known as the Web
• Collection of hyperlinked text documents,
audio, and video files, and remote sites etc.
Accessed via Internet, computers can contact
each other
Public files on computers can be read by
remote user
◦ usually Hypertext Markup Language (.html)
URL - Universal Resource Locator - is name
of file on a remote computer
http://www.microsoft.com
Web Page
◦ Each page available on the website is called a web page.
◦ It is usually written in Hypertext Markup Language (HTML).
◦ It contains text, graphics, images, videos and may also contain
hyperlinks to other web pages.
◦ It is identified by a unique URL (Uniform Resource Locator).
URL is the the unique address of any document available on the
web.
Website
◦ A collection of several related web pages written in HTML markup
language.
Home Page
◦ The first page of any website is called home page.
Web Server
A machine that responds to client requests and sends the requested page
back to user.
popular web server software:
• Apache: www.apache.org
• Web Browser
• Web browser is a software tool used to access and search
information on web.
• Some of popular web browser software are:
• Mozilla Firefox: getfirefox.co
• Microsoft Internet Explorer (IE): part of Windows
• Apple Safari: part of Mac OS X
• Opera: opera.com
• Google Chrome
• Hypertext Markup Language (HTML/XHTML):
• used for writing web pages
• Cascading Style Sheets (CSS):
• supplies stylistic info to web pages
• JavaScript: allows to program the behavior of web pages
• Hypertext Preprocessor (PHP): allows the web server to create pages
dynamically
• Structured Query Language (SQL): interaction with databases
Personal websites
◦ These websites are used by people for their personal use such as to
share information about themselves or their products, to enhance their
skills or post their curriculum vitae online to improve their chances of
getting a job.
◦ Another most common use is to publish virtual journals called blogs that
describe events in people’s lives, their interests and their personal
opinions on different topics.
Professional websites
◦ These are created as portals that provide platform for businesses and
provide information on their products and services. Some of these portals
enable businesses to sell products online and act as virtual storefronts
for receiving orders and payment.
◦ Such sites can directly generate revenue for businesses.
Static websites are developed with fixed-content pages that do not contain
any programmatically controlled content.
Fixed contents pages are pages with content that does not change
dynamically.
The content will only change when the website designer manually modifies
it.
Dynamic websites are driven by dynamic content that is loaded or created
using programming and databases.
Database
◦ Collection of related data stored on a
particular topic
◦ Storage and retrieval is in an organized and
efficient way
◦ Examples: Hospital database, Library
database, Student database etc.
Database Management System (DBMS)
◦ Collection of programs that allows users to
create and maintain a database
◦ Examples: MS Access, MySQL, DB2, SQL
Server etc.
Ø Databases are established technology for managing large
amounts of data.
Ø Achieving complete separation between your site's design and the
content you want to present.
Ø Interaction in real time
A database-driven Web site is a
Web site that uses a database to
gather, display, or manipulate
information
Examples:
◦ News sites: CNN.com and
MSNBC.com
◦ E-commerce companies:
Amazon.com, which is a Web
interface of a big-sized
database system containing
customer and transactional
information.
Client
(Browser)
Web
Server
Database
Server
HTTP request
SQL query
SQL result
HTML page
◦ Databases
MS Access
MySQL, mSQL
Oracle, Sybase, MS SQL Server
◦ Integration tools
PHP or CGI, Servlets, JSP, ASP etc.
• Hyper Text Markup Language
• Syntax
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
• An HTML table is used to organize data in the form of rows and columns.
• The <table> tag is used to create a table in HTML.
• The table rows are created using <tr> tag and <td> tag is used to create
data cells.
• Table headings can be created using <th> tag.
• The <caption> tag is used to set the title for the table at the top of table.
• The border is an attribute of <table> tag which is used to put a border
across all the cells of the table.
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<table border="1">
<caption>This is Sample Table.</caption>
<th>Heading 1</th>
<th>Heading 2</th>
<tr>
<td>This is Row 1, This is Column 1</td>
<td>This is Row 1, This is Column 2</td>
</tr>
<tr>
<td>This is Row 2, This is Column 1</td>
<td>This is Row 2, This is Column 2</td>
</tr>
</table>
</body>
</html>
Output
• The background of a table can be set using any of the following two ways:
• bgcolor attribute : Using this attribute, you can set background color of the
table.
• background attribute :Using this attribute, you can set background image.
• bordercolor attribute: Using this attribute, you can set border color.
• Syntax
• Update the <table> tag of above code as given below then see the
output.
• <table border="1" bordercolor="red" bgcolor="yellow">
• Output:
• colspan attribute is used to merge two or more columns into a single column.
• Rowspan is used merge two or more rows.
• Syntax
• <TH COLSPAN = “2”>
• <TD ROWSPAN = “2”>
• Example
<table border="1">
<caption>This is Sample Table.</caption>
<th colspan= "2">Heading 1</th>
<tr>
<td>This is Row 1, This is Column 1</td>
<td>This is Row 1, This is Column 2</td>
</tr>
<tr>
<td>This is Row 2, This is Column 1</td>
<td>This is Row 2, This is Column 2</td>
</tr>
</table>
• HTML Forms are required when you want to collect some data from the site
visitor. For example during user registration you would like to collect
information such as name, email address, credit card, etc.
• A form will take input from the site visitor and then will post it to a back-end
application such as CGI, ASP Script or PHP script etc. The back-end
application will perform required processing on the passed data based on
defined business logic inside the application.
• <form> and </form> tags are used to created form; all form controls are
placed in between these opening and closing tags.
• A form tag usually consists of following attributes:
• Action: “url”
• It specifies the location where we have to send our data when Submit
button is clicked.
• method="get“ or “Post”
• Get for search forms and forms where results need to be retrieved.
• Post for feedback forms and forms where results need to be sent.
• target="target"
• This specifies where our page will be opened
• target= _blank means open page in a new window
• target= _top means open the page in the same window
• Following are some commonly used attributes for input fields.
• MAXLENGTH
• Allows to specify the maximum number of characters a user can enter
into the text box.
• NAME
• Used to give a name to the control which is sent to the server to be
recognized and get the value.
• TYPE
• Indicates the type of input control and for text input control it will be set
to text.
• VALUE
• This can be used to provide an initial value inside the control.
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form action="demo.php" method="get">
Name: <input type="text" name="name"><br>
Father Name: <input type="text" name="fname"><br>
Gender: <input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="male"> Male <br>
Email Address: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Before you continue you should have a basic
understanding of the following:
HTML
CSS
JavaScript
PHP is an abbreviation for "PHP: Hypertext
Preprocessor"
PHP is a widely used, open source scripting
language
PHP scripts are executed on the server
PHP is free to download and use
PHP files can contain text, HTML, CSS,
JavaScript, and PHP code
PHP code are executed on the server, and the
result is returned to the browser as plain
HTML
PHP files have extension ".php"
PHP runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers
used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP
resource: www.php.net
PHP is easy to learn and runs efficiently on
the server side
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and
close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your
database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML.
You can output images, PDF files, and even
Flash movies. You can also output any text,
such as XHTML and XML.
To start using PHP, you can:
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then
install PHP and MySQL
If your server has activated support for PHP
you do not need to do anything.
Just create some .php files, place them in
your web directory, and the server will
automatically recognize them and execute.
You do not need to compile anything or
install any extra tools.
Because PHP is free, most web hosts offer
PHP support.
If your server does not support PHP, you must:
install a web server
install PHP
install a database, such as MySQL
The official PHP website (PHP.net) has
installation instructions for
PHP:http://php.net/manual/en/install.php
PHP program can be run under various like
WAMP, XAMPP etc.
WAMP Server: this server is a web
development platform which helps in creating
dynamic web applications.
XAMPP Server: It is a free open source crossplatform web server package.
you can download it from the following link:
http://www.apachefriends.org/en/xamppwindows.html
After downloading, just follow the following
step to start xampp server:
Step1
Install XAMPP
Step2
Assume you installed xampp in C Drive.
Go to: C:\xampp\htdocs
Create your own folder, name it for example
as PHPCode.
Step3
Now create your first php program in xampp
and name it as “add.php”:
<html>
<head><title>Addition php</title></head>
<body>
<?php # operator
print "<h2>php program to add two
numbers...</h2><br />";
$val1 = 20;
$val2 = 20;
$sum = $val2 + $val2; /* Assignment operator */
echo "Result(SUM): $sum"; ?>
</body>
</html>
Step4
Now double click on “XAAMP CONTROL
PANEL” on desktop and START “Apache”
(icon also appears on the bottom)
(XAAMP Control Panel Screenshot is on next
slide)
Step5
Type localhost on your browser and press
enter:
It will show the following Screen:
Step6
Now type the following on browser:
http://localhost/ PHPCode /
Below screenshot shows php files created
under folder “PHPCode”
Step7
Click on “add.php” and it will show the
following:
A PHP script can be placed anywhere in the
document.
A PHP script starts with <?php and ends with
?>
The default file extension for PHP files is
".php".
A PHP file normally contains HTML tags, and
some PHP scripting code.
Below, we have an example of a simple PHP file,
with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!"
on a web page:
Code
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
My first PHP page
Hello World!
A comment in PHP code is a line that is not
read/executed as part of the program.
Its only purpose is to be read by someone
who is looking at the code.
Remind yourself of what you did.
PHP supports several ways of commenting.
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
In PHP, all keywords (e.g. if, else, while, echo,
etc.), classes, functions, and user-defined
functions are NOT case sensitive.
In the example below, all three echo
statements below are legal (and equal):
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Hello World!
Hello World!
Hello World!
All variable names are case-sensitive.
In the example below, only the first statement
will display the value of the $color variable
(this is because $color, $COLOR, and $coLOR
are treated as three different variables):
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
My car is red
My house is // it does not show color name
My boat is // it does not show color name
Variables can store data of different types, and
different data types can do different things.
PHP supports the following data types:
String
Integer
Float (double)
Boolean
Array
Object
NULL
A string is a sequence of characters, like "Hello
world!".
A string can be any text inside quotes. You can
use single or double quotes:
PHP Code
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hello world!
Hello world!
An integer is a whole number (without
decimals). It is a number between -
2,147,483,648 and +2,147,483,647.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
In the following example $x is an integer. The
PHP var_dump() function returns the data
type and value:
<?php
$x = 598;
var_dump($x);
?>
Output
int(598)
A float (floating point number) is a number
with a decimal point or a number in
exponential form.
In the following example $x is a float. The
PHP var_dump() function returns the data
type and value:
<?php
$x = 10.365;
var_dump($x);
?>
<?php
$x = 10.365;
var_dump($x);
?>
Output :
float(10.365)
A Boolean represents two possible states:
TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing
An array stores multiple values in one single
variable.
In the following example $cars is an array.
The PHP var_dump() function returns the data
type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
array(3) { [0]=> string(5) "Volvo" [1]=>
string(3) "BMW" [2]=> string(6) "Toyota" }
Null is a special data type which can have
only one value: NULL.
A variable of data type NULL is a variable that
has no value assigned to it.
Note: If a variable is created without a value,
it is automatically assigned a value of NULL.
Variables can also be emptied by setting the
value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
An object is a data type which stores data and
information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For
this, we use the class keyword. A class is a
structure that can contain properties and
methods:
<?php
class Car {
function Car() {
$this->model = "VW";
}}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
PHP Variables
Variables are "containers" for storing
information.
How to Declare PHP Variables
In PHP, a variable starts with the $ sign,
followed by the name of the variable:
Examples :
$txt = "Hello world!";
$x = 5;
$y = 10.5;
A variable can have a short name (like x and
y) or a more descriptive name (age, carname,
total_volume.
A variable starts with the $ sign, followed by
the name of the variable
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alphanumeric characters and underscores (A-z, 0-
9, and _ )
Variable names are case-sensitive ($age and
$AGE are two different variables)
Note : Remember that PHP variable names are
case-sensitive!
The PHP echo statement is often used to
output data to the screen.
The following example will show how to
output text and a variable:
<?php
$txt = “Pakistan";
echo "I love $txt!";
?>
Output will be
I love Pakistan!
Another example for variable addition:
Code :
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP automatically converts the variable to the
correct data type, depending on its value.
In other languages such as C, C++, and Java,
the programmer must declare the name and
type of the variable before using it.
PHP Variables Scope
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
A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function:
Example:
<?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>";
?>
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that
function:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an
error
echo "<p>Variable x outside function is: $x</p>";
?>
Variable x inside function is: 5
Variable x outside function is:
The global keyword is used to access a global
variable from within a function.
To do this, use the global keyword before the
variables (inside the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Normally, when a function is
completed/executed, all of its variables are
deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a
further job.
To do this, use the static keyword when you
first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
0 1 2
Note : Then, each time the function is called,
that variable will still have the information it
contained from the last time the function was
called.
The real power of PHP comes from its functions;
it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create
our own functions.
A function is a block of statements that can be
used repeatedly in a program.
A function will not execute immediately when a
page loads.
A function will be executed by a call to the
function.
A user defined function declaration starts with the
word "function":
Syntax
function functionName() {
code to be executed;
}
A function name can start with a letter or
underscore (not a number).
Give the function a name that reflects what
the function does.
Function names are NOT case-sensitive.
<?php
function writeMsg() {
echo “Welcome to PHP Page!";
}
writeMsg(); // call the function
?>
OutPut
Welcome to PHP Page
Information can be passed to functions
through arguments. An argument is just like
a variable.
Arguments are specified after the function
name, inside the parentheses. You can add as
many arguments as you want, just separate
them with a comma.
The following example has a function with one
argument ($fname). When the familyName()
function is called, we also pass along a name
(e.g.Ali), and the name is used inside the
function, which outputs several different first
names, but an equal last name:
<?php
function familyName($fname) {
echo "$fname Ahmed.<br>";
}
familyName(“Ali");
familyName(“Usman");
familyName(“Hafeez");
?>
Output:
Ali Ahmed
Usman Ahmed
Hafeez Ahmed
<?php
function familyName($fname, $year) {
echo "$fname Ahmed. Born in $year <br>";
}
familyName(“Ali", "1975");
familyName(“Usman", "1978");
familyName(“Hafeez", "1983");
?>
Output:
Ali Ahmed. Born in 1975
Usman Ahmed. Born in 1978
Hafeez Ahmed. Born in 1983
The following example shows how to use a
default parameter. If we call the function
setHeight() without arguments it takes the
default value as argument:
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
?>
Output :
The height is : 350
The height is : 50
The height is : 135
To let a function return a value, use the
return statement:
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
?>
Output:
5 + 10 = 15
7 + 13 = 20
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.
In PHP we have the following conditional
statements:
if statement
if...else statement
if...elseif....else statement
switch statement
The if statement is used to execute some
code only if a specified condition isis true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good
day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Output :
Have a good day!
Use the if....else statement to execute some
code if a condition isis true and another code if
the condition isis false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good
day!" if the current time is less than 20, and
"Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Use the if....elseif...else statement to specify a
new condition to test, if the first condition isis
false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good
morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output :
The hour (of the server) is 03, and will give
the following message:
Have a good morning!
The switch statement is used to perform
different actions based on different
conditions.
Use the switch statement to select one of
many blocks of code to be executed.
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;
}
Ø How switch statement 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.
<?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":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Output:
Your favorite color is red!
In computer programming, a loop is a
sequence of instruction s that is continually
repeated until a certain condition is reached.
PHP Loops :
In PHP, we have the following looping
statements:
while
do...while
for
foreach
The while loop executes a block of code as
long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The do...while loop will always execute the
block of code once, it will then check the
condition, and repeat the loop while the
specified condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x
= 1). Then, the do while loop will write some
output, and then increment the variable $x with 1.
Then the condition is checked (is $x less than, or
equal to 5?), and the loop will continue to run as
long as $x is less than, or equal to 5:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The example below sets the $x variable to 6,
then it runs the loop, and then the condition
isis checked.
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
Output
The number is: 6
The for loop is used when you know in
advance how many times the script should
run.
Syntax
for (init counter; test counter; increment
counter) {
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop
iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop
ends.
increment counter: Increases the loop counter
value
The example below displays the numbers
from 0 to 10:
<?php
for ($x = 0; $x <= 5; $x++) {
echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The foreach loop works only on arrays, and is
used to loop through each key/value pair in
an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
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):
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Output:
red
green
blue
yellow
An array stores multiple values in one single
variable.
Example:
<?php
$cars = array(“Honda Civic", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
Output:
I like Honda Civic, BMW and Toyota
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 = “Honda Civic";
$cars2 = "BMW";
$cars3 = "Toyota";
An array can hold many values under a single
name, and you can access the values by
referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create
an array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing
one or more arrays
There are two ways to create indexed arrays:
The index can be assigned automatically
(index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed
array named $cars, assigns three elements to
it, and then prints a text containing the array
values:
<?php
$cars = array(“Swift", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and "
. $cars[2] . ".";
?>
I like Swift, BMW and Toyota.
The count() Function:
The count() function is used to return the
length (the number of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output:
3
To loop through and print all the values of an
indexed array, you could use a for loop, like this:
<?php
$cars = array(“Swift", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Swift
BMW
Toyota
Associative arrays are arrays that use named
keys that you assign to them.
There are two ways to create an associative
array:
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
OR
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output:
Peter is 35 years old.
To loop through and print all the values of an
associative array, you could use a foreach loop, like
this:
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.
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
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.
The dimension of an array indicates the
number of indices you need to select an
element. For a two dimensional array you
need two indices to select an element
For a three dimensional array you need three
indices to select an element
Name Stock Sold
Volvo 22 18
BMW 15 13
Swift 5 2
Land Rover 17 15
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Swift",5,2),
array("Land Rover",17,15)
);
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
A string is a sequence of characters, like "Hello
world!".
PHP String Functions:
Get The Length of a String
The PHP strlen() function returns the length of a
string.
The example below returns the length of the string
"Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Output:
12
Count The Number of Words in a String
The PHP str_word_count() function counts the
number of words in a string:
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
The output of the code above will be: 2.
Reverse a String
The PHP strrev() function reverses a string:
<?php
echo strrev("Hello world!");
// outputs !dlrow olleH
?>
Search For a Specific Text Within a String
The PHP strpos() function searches for a specific
text within a string.
If a match is found, the function returns the
character position of the first match. If no match is
found, it will return FALSE.
The example below searches for the text "world"
in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The output of the code above will be: 6.
Note: The first character position in a string is 0
(not 1).
Replace Text Within a String
The PHP str_replace() function replaces some
characters with some other characters in a string.
The example below replaces the text "world" with
"Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!");
// outputs Hello Dolly!
?>
Basic Concepts of OOP
Object-Oriented Programming (OOP) is a type
of programming added to php5 that makes
building complex, modular and reusable web
applications that much easier.
There are some basic concepts about OOP
Which are as follows :
Class
Object
Member Variable
Member function
Inheritance
Parent class.
Child Class.
Polymorphism
Overloading
Data Abstraction
Encapsulation
Constructor
Destructor
Class :This is a programmer-defined data type,
which includes local functions as well as local
data. You can think of a class as a template for
making many instances of the same kind (or
class) of object.
Object An individual instance of the data
structure defined by a class. You define a class
once and then make many objects that belong
to it. Objects are also known as instance.
Member Variable : These are the variables
defined inside a class. This data will be
invisible to the outside of the class and can
be accessed via member functions. These
variables are called attribute of the object
once an object is created.
Member function : These are the function
defined inside a class and are used to access
object data.
Inheritance : When a class is defined by
inheriting existing function of a parent class
then it is called inheritance. Here child class
will inherit all or few member functions and
variables of a parent class.
Parent class : A class that is inherited from by
another class. This is also called a base class
or super class.
Child Class: A class that inherits from another
class. This is also called a subclass or derived
class
Polymorphism: This is an object oriented
concept where same function can be used for
different purposes. For example function
name will remain same but it make take
different number of arguments and can do
different task.
Overloading : a type of polymorphism in
which some or all of operators have different
implementations depending on the types of
their arguments. Similarly functions can also
be overloaded with different implementation.
Data Abstraction : Any representation of data in
which the implementation details are hidden
(abstracted).
Encapsulation : refers to a concept where we
encapsulate all the data and member functions
together to form an object.
Constructor : refers to a special type of function
which will be called automatically whenever there
is an object formation from a class.
Destructor : refers to a special type of function
which will be called automatically whenever an
object is deleted or goes out of scope.
First thing we need to do is create two PHP
pages:
index.php
class_lib.php
OOP is all about creating modular code, so our
object oriented PHP code will be
contained in dedicated files that we will then
insert into our normal PHP page using
php 'includes'. In this case all our OO PHP code
will be in the PHP file:
class_lib.php
You define your own class by starting with
the keyword 'class' followed by the name
you want to give your new class.
<?php
class person {
}
One of the big differences between functions and
classes is that a class contains both data
(variables) and functions that form a package
called an: 'object'. When you create a
variable inside a class, it is called a 'property'.
<?php
class person {
var $name;
}
Note: The data/variables inside a class (var
$name;) are called 'properties'.
In the same way that variables get a different
name when created inside a class(they are
called: properties,) functions also referred to
by a different name when created inside a
class they are called 'methods'.
A classes' methods are used to manipulate
its' own data / properties.
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name; }
}
We have created two interesting
functions/methods:
get_name() and set_name().
STEP 6: The '$this' variable
The $this is a built-in variable (built into all
objects) which points to the current
object. Or in other words, $this is a special
self-referencing variable.
You use $this to access properties and to call
other methods of the current class.
function get_name() {
return $this->name;
}
You would never create your PHP classes
directly inside your main php pages.
Instead, it is always best practice to create
separate php pages that only contain
your classes.
Then you would access your php
objects/classes by including them in your
main php pages with either a php 'include' or
'require'.
<html>
<head>
<title>OOP in PHP</title>
<?php include("class_lib.php"); ?>
</head>
<body>
</body>
</html>
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
?>
</body>
</html>
The variable $stefan becomes a
handle/reference to our newly created person
object.
STEP 9: The 'new' keyword
To create an object out of a class, you need
to use the 'new' keyword.
When creating/instantiating a class, you can
optionally add brackets to the class name.
As we did in the example below. To be clear,
you can see in the code below how we can
create multiple objects from the same class.
<body>
<?php
$stefan = new person();
$jimmy = new person();
?>
</body>
We have created our two separate 'person'
objects, we can set their properties using the
methods (the setters) we created.
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
}
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name(“ Jimmy Nick");
?>
</body>
</html>
<?php include("class_lib.php"); ?>
</head>
<body>
<?php$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
echo "Stefan's full name: " . $stefan->get_name();
echo "Nick's full name: " . $jimmy->get_name();
?>
</body>
</html>
You don't have to use methods to access
objects properties; you can directly get to
them using the arrow operator (->) and the
name of the variable.
See Example on next slide
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
echo "Stefan's full name: " . $stefan->name;
?>
</body>
</html>
All objects can have a special built-in method
called a 'constructor'. Constructors allow you
to initialize your object's properties.
The 'construct' method starts with two
underscores (__) and the word 'construct'.
You 'feed' the constructor method by
providing a list of arguments (like a function)
after the class name.
<?php
2. class person {
3. var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function set_name($new_name) {
$this->name = $new_name;
}
Now that we've created a constructor method, we
can provide a value for the $name property when
we create our person objects.
For example: $stefan = new person("Stefan
John");
<?php
$stefan = new person("Stefan Mischook");
echo "Stefan's full name: " $stefan->get_name();
?>
</body>
</html>
Note: This saves us from having to call the set_name()
method reducing the amount of code.
One of the fundamental principles in OOP is
'encapsulation'. The idea is that you create
cleaner better code, if you restrict access to the
data structures (properties) in your objects.
You restrict access to class properties using
something called 'access modifiers'.
There are 3 access modifiers:
• public
• private
• protected
Public is the default modifier.
<?php
class person {
var $name;
public $height;
protected $social_insurance;
private $pinn_number;
}
>
Note: When you declare a property with the
'var' keyword, it is considered 'public
When you declare a property as 'private', only
the same class can access the property.
When a property is declared 'protected', only
the same class and classes derived from that
class can access the property - this has to do
with inheritance …more on that later.
Properties declared as 'public' have no access
restrictions, meaning anyone can access
them.
Like properties, you can control access to
methods using one of the three access
modifiers:
public
protected
private
Doing this allows you to efficiently reuse the
code found in your base class.
<?php
// 'extends' is the keyword that enables
inheritance
class employee extends person {
function __construct($employee_name) {
}
}
?>
Sometimes (when using inheritance,) you may
need to change how a method works from
the base class.
For example, let's say set_name() method in
the 'employee' class, had to do something
different than what it does in the 'person'
class.
Using :: allows you to specifically name the class
where you want PHP to search for
a method - 'person::set_name()' tells PHP to search
for set_name() in the 'person‘ class.
<?php
/* explicitly adding class properties are optional -
but is good practice */
class person {
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function get_name() {
return $this->name;
}
// protected methods and properties restrict
//access to those elements
protected function set_name($new_name) {
if (name != "Jimmy Two Guns") {
$this->name = strtoupper($new_name); }
}
}
protected function set_name($new_name) {
if ($new_name == "Stefan Lamp") {
$this->name = $new_name;
}
else if($new_name == "Johnny Fingers") {
parent::set_name($new_name);
}
}
function __construct($employee_name) {
$this->set_name($employee_name); }
}
?>
One of the cool features of PHP is the huge
collection of built-in functions it provides.
You can call these functions anywhere in your
scripts without defining.
$amount = 537.1267;2.
$newAmount=round($amount, 2);
// output will be 537.13
Working with date() function
Date() is a built-in php function for showing
date. we can pass it many different
values/arguments.
Here some examples: */
echo "<p>". date("D") ."</p>";
//Day name in three letters => Tue
echo "<p>". date("M") ."</p>";
//Month name in three letters => Dec
/* Here some examples of functions to check
a variable data type: */
is_int($variable)
//check if is INTEGER, returns a Boolean (true/false)
is_float($variable)
//check if is FLOAT, returns a Boolean (true/false)
is_string($variable)
//check if is STRING, returns a Boolean (true/false)
/* isset() allows you to check if a variable has
been previously set: */
isset($variable)
// returns a Boolean (true/false)
/* Here some examples of functions to use to
handle form data: */
strval(intval($variable))
//STRVAL gets the string value of a variable
strval(floatval($variable))
/*INTVAL and FLOATVAL get the integer/float
value of a var */
addslashes($variable)
// Escape single quote with a back slash
stripslashes($variable)
// Escape back slash from string
The Standard PHP Library (SPL) is where PHP
5's object-oriented capabilities truly shine. It
improves the language in five key ways:
iterators, exceptions, array overloading, XML,
and file and data handling.. Additionally, it
offers advanced functionality for autoloading classes and interfaces.
class_implements — Return the interfaces
which are implemented by the given class or
interface
class_parents — Return the parent classes of
the given class
iterator_apply — Call a function for every
element in an iterator
iterator_count — Count the elements in an
iterator
iterator_to_array — Copy the iterator into an
array
When you work with an application, you open
it, do some changes, and then you close it.
This is much like a Session. The computer
knows who you are. It knows when you start
the application and when you end. But on the
internet there is one problem: the web server
does not know who you are or what you do,
because the HTTP address doesn't maintain
state.
Session variables solve this problem by
storing user information to be used across
multiple pages (e.g. username, favorite color,
etc). By default, session variables last until
the user closes the browser.
So Session variables hold information about
one single user, and are available to all pages
in one application
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Example :
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html> // output : Session variables are set.
Next, we create another page called
"demo_session2.php". From this page, we will
access the session information we set on the
first page ("demo_session1.php").
Notice that session variables are not passed
individually to each new page, instead they
are retrieved from the session we open at the
beginning of each page (session_start()).
Also notice that all session variable values are
stored in the global $_SESSION variable:
<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Output :
Favorite color is green.
Favorite animal is cat.
To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html> //output : Array ( [favcolor] => yellow [favanimal] => cat )
To remove all global session variables and destroy the
session, use session_unset() and session_destroy():
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
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
A cookie is created with the setcookie()
function.
Syntax
setcookie(name, value, expire, path, domain,
secure, httponly);
Only the name parameter is required. All
other parameters are optional.
The given example creates a cookie named
"user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/"
means that the cookie is available in entire
website (otherwise, select the directory you
prefer).
We then retrieve the value of the cookie "user"
(using the global variable $_COOKIE). We also
use the isset() function to find out if the
cookie is set:
<?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];
}
?>
</body>
</html.
Note: The setcookie() function must appear BEFORE the <html> tag.
Cookie named 'user' is not set!
Note: You might have to reload the page to
see the value of the cookie
To modify a cookie, just set (again) the cookie using the setcookie()
function:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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];
}
?>
</body>
</html>
Output :
Cookie 'user' is set!
Value is: John DoeNote: You might have to
reload the page to see the new value of the
cookie.
To delete a cookie, use the setcookie() function with an
expiration date in the past:
<html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Output: Cookie 'user' is deleted.
The following example creates a small script that checks whether
cookies are enabled. First, try to create a test cookie with the
setcookie() function, then count the $_COOKIE array variable:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
output : Cookies are enabled
Exceptions are used to change the normal flow of
a script if a specified error occurs.
This is what normally happens when an
exception is triggered:
The current code state is saved.
The code execution will switch to a predefined
(custom) exception handler function.
Depending on the situation, the handler may
then resume the execution from the saved code
state, terminate the script execution or continue
the script from a different location in the code.
When an exception is thrown, the code
following it will not be executed, and PHP will
try to find the matching "catch" block.
If an exception is not caught, a fatal error will
be issued with an "Uncaught Exception"
message.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or
below");
}
return true;
}
//trigger exception
checkNum(2);
?>
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in
C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in
C:\webfolder\test.php on line 6
To avoid the error from the example above, we
need to create the proper code to handle an
exception.
Proper exception code should include:
Try - A function using an exception should be in
a "try" block. If the exception does not trigger,
the code will continue as normal. However if the
exception triggers, an exception is "thrown"
Throw - This is how you trigger an exception.
Each "throw" must have at least one "catch"
Catch - A "catch" block retrieves an exception
and creates an object containing the exception
information
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
The code above throws an exception and
catches it:
The checkNum() function is created. It checks
if a number is greater than 1. If it is, an
exception is thrown
The checkNum() function is called in a "try"
block
The exception within the checkNum()
function is thrown
The "catch" block retrieves the exception and
creates an object ($e) containing the
exception information
The error message from the exception is
echoed by calling $e->getMessage() from the
exception object
However, one way to get around the "every
throw must have a catch" rule is to set a top
level exception handler to handle errors that
slip through.
• Open the XAMPP Control Panel.
• To turn Apache and mySQL on/off, simply click the respective start/stop
buttons for each component.
• The buttons will change state depending on the status of the component.
• Open your browser and go to http://localhost/.
• XAMPP welcome screen
phpMyAdmin
• Database is an organized collection of related data. For example, hospital
database, school database etc..
• Relation databases
• A relational database (RDB) is a collective set of multiple data sets
organized by tables, records and columns.
• Each table is known as a relation.
• RDBs establish a well-defined relationship between database tables.
• DBMS
• A database management system (DBMS) is system software for creating
and managing databases.
• It provides users and programmers with a systematic way to create,
retrieve, update and manage data.
1. Table Columns
Rows
3. Primary Key
• It is a special relational database table column (or combination of
columns) designated to uniquely identify all table records.
• It must contain a unique value for each row of data.
• It cannot contain null values.
4. Foreign Key
• It is a column (or columns) that references a column (most often the
primary key) of another table.
• It ensures referential integrity of the data.
5. Referential Integrity
• It requires every value of one attribute of a relation to exist as a value of
another attribute in a different relation.
• mySQL is an open source Relational Database Management System
that uses Structured Query Language (SQL).
• It is very fast, reliable, scalable, and easy to use.
• It works on many operating systems and with many languages
including PHP, PERL, C, C++, JAVA, etc.
• It is very friendly to PHP, the most appreciated language for web
development.
• It supports large databases.
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
die() function
• The die() function prints a message and exits the current script.
• This function is an alias of the exit() function.
mysql_error () function
• Returns the text of the error message from previous MySQL operation
mysql_close() function
• closes the non-persistent connection to the MySQL server
• Open non-persistent MySQL connections and result sets are automatically
destroyed when a PHP script finishes its execution
• PHP uses mysql_query function to create or delete a MySQL database.
This function takes two parameters and returns TRUE on success or
FALSE on failure.
• Syntax:
• bool mysql_query( sql, connection );
• Parameters
• Description
• Sql
• Required - SQL query to create or delete a MySQL database
• Connection
• Optional - if not specified, then last opened connection by mysql_connect
will be used.
• <html>
• <head>
• <title>Creating MySQL Database</title>
• </head>
• <body>
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn )
• {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully<br />';
• $sql = 'CREATE DATABASE TUTORIALS';
• $retval = mysql_query( $sql, $conn );
• if(! $retval )
• {
• die('Could not create database: ' . mysql_error());
• }
• echo "Database TUTORIALS created successfully\n";
• mysql_close($conn);
• ?>
• </body>
• </html>
• CHAR(size)
• It holds a fixed length string specified in parenthesis.
• It can store up to 255 characters
• It can contain letters, numbers, and special characters.
• VARCHAR(size)
• It holds a variable length string, specified in parenthesis.
• It can store up to 255 characters.
• It can contain letters, numbers, and special characters.
• AutoNumber
• It automatically gives each record its own number, usually starting at 1
• INT(size)
• Range is -2147483648 to 2147483647.
• 0 to 4294967295 UNSIGNED.
• The maximum number of digits may be specified in parenthesis
• FLOAT(size,d)
• A small number with a floating decimal point.
• The maximum number of digits may be specified in the size parameter.
• The maximum number of digits to the right of the decimal point is specified in
the d parameter
• DATE()
• A date.
• Format: YYYY-MM-DD
• The supported range is from '1000-01-01' to '9999-12-31'
• DATETIME()
• A date and time combination.
• Format: YYYY-MM-DD HH:MI:SS
• TIME()
• A time. Format:
• HH:MI:SS
• The supported range is from '-838:59:59' to '838:59:59'
• YEAR()
• A year in two-digit(15) or four-digit format(2015).
• optional attributes for each column:
• NOT NULL
• Each row must contain a value for that column
• null values are not allowed
• firstname VARCHAR(30) NOT NULL;
• DEFAULT value
• Set a default value that is added when no other value is passed
• Gender VARCHAR(20) DEFAULT “Female”
• UNSIGNED
• Used for number types
• Limits the stored data to positive numbers and zero
• Salary INT(6) UNSIGNED NOT NULL
• AUTO INCREMENT
• mySQL automatically increases the value of the field by 1 each time a
new record is added
• id INT(6) UNSIGNED AUTO_INCREMENT;
• PRIMARY KEY
• Used to uniquely identify the rows in a table.
• The column with PRIMARY KEY setting is often an ID number and is
often used with AUTO_INCREMENT.
• id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
• FOREIGN KEY
• It points to a PRIMARY KEY in another table.
• FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
The table creation command requires:
• Name of the table
• Names of fields
• Definitions for each field
Syntax:
• Here is generic SQL syntax to create a MySQL table:
CREATE TABLE table_name (column_name column_type);
• CREATE TABLE tutorials_tbl(
• tutorial_id INT NOT NULL AUTO_INCREMENT,
• tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
• submission_date DATE,
• PRIMARY KEY ( tutorial_id )
• Select
• Insert
• Update
• Delete
• INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
• SELECT column_name(s) FROM table_name
• SELECT * FROM table_name
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
• DELETE FROM table_name
WHERE some_column = some_value
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
• UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
• <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
• The main functionality of the PhpMyAdmin tool is to manage your
databases.
• Click on the Databases link and create the database or Pick the preferred
database which you want to manage and click on its name.
• Create the new Table
• CREATE TABLE `employee` ( `id` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT
NULL, `job_title` varchar(100) DEFAULT NULL, `salary` double DEFAULT
NULL, `notes` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT
CHARSET=utf8;
• You will see the fields' names, their types, collations, attributes, additional
extra information, the default values and whether the fields' values can be
NULL. You can browse for distinct values by clicking on the corresponding
action icon. Also, you can edit a field's structure or delete a field. You can
define different indexes: Primary, Unique, Index and Fulltext.
• In the Indexes area you will find the indexes assigned for the table and the
fields for which they are set. You can edit and delete them.
• Only the tables with existing records can be browsed. Once you click on the
Browse icon a new window with the records list will be opened.
• By clicking on the Pen icon you can edit the chosen record.
• You will see the record structure and you can alter the values of the
records.
Using the Insert action you can insert records in your database table.
INSERT INTO `employee` (`first_name`, `last_name`, `job_title`, `salary`)
VALUES (‘Ali', ‘Imran', 'Software Engineer', 5500), (‘khalid', ‘Mehmood',
'Software Architect', 7200), (‘Danish', ‘Husnain', 'Database Administrator',
6000), (‘Muhammad', ‘Aryan', 'Database Administrator', 6800), (‘Hameed',
‘Gul', 'Software Engineer', 4750), (‘Sara', ‘Ali', 'Software Engineer', 5100),
(‘Hina', ‘Waseem', 'Project Manager', 8500), (‘Iqra', ‘Husnain', 'Software
Architect', 8000);
• Once you fill in the corresponding values click on the Go button and the
new record will be inserted.
• Relational databases provide lots of options and power for indices and
keys:
• a index on 1 / several columns can dramatically improve performance
• you can designate an index as unique (duplicates are rejected at runtime)
• the Primary Key is the main unique index.
• Auto_Increment Primary Keys
• Many database designers elect to define a column (often called Id) as a
system-computed AUTO_INCREMENT. This is also called a surrogate
key (as distinct from a natural key).
• This can simplify your database design, as shown for employee, below:
• You define a Relationship by defining a Foreign Key, wherein the child
contains the Primary Key of the Parent.
• To define a Foreign Key Relationship:
• Create an index on the Child Column(s) that comprise the Foreign Key
• Create the Relationship.Note there is substantial power in the Cascade
rules.
• Create the Relationship by selecting the Child Table > Structure > Relation
View:
• In our example, the employee_education (child) contains a field
(education_id) that matches the Primary Key of the Employee (parent),
the Id.
• CREATE TABLE `employee_education` (
• `employee_id` int NOT NULL,
• `education_id` tinyint NOT NULL
• ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
• INSERT INTO `employee_education` (`employee_id`, `education_id`)
VALUES
• (1, 1),
• (2, 1),
• (3, 2),
• (3, 3);
CASCADE
• Whenever rows in the master (referenced) table are deleted (resp.
updated), the respective rows of the child (referencing) table with a
matching foreign key column will get deleted as well. This is called a
cascade delete.
RESTRICT
• A value cannot be updated or deleted when a row exists in a foreign key
table that references the value in the referenced table. Similarly, a row
cannot be deleted as long as there is a reference to it from a foreign key
table.
NO ACTION
• NO ACTION and RESTRICT are very much alike. The main difference
between NO ACTION and RESTRICT is that with NO ACTION the
referential integrity check is done after trying to alter the table. RESTRICT
does the check before trying to execute the UPDATE or DELETE
statement. Both referential actions act the same if the referential integrity
check fails: the UPDATE or DELETE statement will result in an error.
SET NULL
• The foreign key values in the referencing row are set to NULL when the
referenced row is updated or deleted. This is only possible if the respective
columns in the referencing table are nullable. Due to the semantics of
NULL, a referencing row with NULLs in the foreign key columns does not
require a referenced row.
• The WHERE clause is used to filter records.
Syntax
• SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
• = (Equal)
• <>(Not equal (Also written as !=))
• > (Greater than)
• < (Less than)
• >= (Greater than or equal)
• <= (Less than or equal)
• BETWEEN
• Between an inclusive range
• Equal
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’;
• Greater
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id>10";
• Less then
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id<10";
• Between
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE id
between 5 AND 10“;
• AND
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ AND lastname=‘Ehsaan’";
• OR
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ OR firstname=‘Pasha’";
• Arrange the results in ascending or descending order.
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE
firstname=‘Ali’ OR firstname=‘Pasha’ ORDERED BY firstname DESC”;
• JOIN clause is used to combine rows from two or more tables, based on a
common field between them.
• Types of joins
• Inner join
• Left join
• Right join
• Inner joins let us select rows that have same value in both tables for
specified columns thereby returns matching rows. We specify the first table
after FROM as in normal SELECT statements and the second table is
specified after INNER JOIN.
• Using ON clause we can specify the columns that should have matching
values.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
For example
• $sql = “SELECT e.first_name, e.last_name, u.user_type, u.username
FROM `employee` INNER JOIN `user` ON e.id = u.employee_id ";
• Left joins let you select all the rows from first table (left table) for specified
relationship and fetch only the matching ones from second table (right
table)
• SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
• $sql = " SELECT e.first_name, e.last_name, u.user_type, u.username
FROM `employee` LEFT JOIN `user` ON e.id = u.employee_id ";
• Right joins work opposite to left joins. That is, priority is given to right table
and fetches all the rows from right table for given relationship.
• SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
• $sql = " SELECT e.first_name, e.last_name, u.user_type,
u.usernameFROM `employee` RIGHT JOIN `user` ON u.employee_id =
e.id ";
• View is a virtual table based on the result-set of an SQL statement
• It contains rows and columns, just like a real table.
• The fields in a view are fields from one or more real tables in the database.
CREATE VIEW SYNTAX
Create view view_name AS
Select column_name(s)
From table_name
Where condition
Example:
create view employee_1 AS select first_name,last_name from employee
where id = 1
Step1:Open your XAMPP control panel and click admin button to get
into PHPMyAdmin window.
Step2: Before connecting MYSQL with PHP we need to create a
database first. Click on database tab and inside the database name
field type a name of VUDATABASE and go with the default setting
which is collation and hit create.
Step3: Open a notepad /dreamweaver and write the PHP script as
shown in snapshot to connect with MYSQL.
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to
the server:
Code:
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “xamp")
or die();
mysql_select_db (“VUDATABASE", $conn) or die( );
echo (" Database connected successfully");
?>
Close the Connection
The connection will be closed automatically when the script ends. To
close the connection before, use the following:
$conn->close();
Display on web site “Connected database successfully”
Step1:Open your XAMPP control panel and click admin button to get
into XAMPP for windows.
Step2: Click on security tab
Step3 Inside the security window field type the password and click on
password changing tab
Step 4:open the phpMyAdmin window and enter the username “root”
and password “xamp”for authentication
There are two ways the browser client can send information to the
web server.
1. The GET Method
2. The POST Method
We see a lot of forms while surfing the internet. Like creating an
email account or subscribe to a newsletter by name/email etc. When
we fill the forms with data, the PHP provides methods to receive it
just like other web based languages.
The GET PHP method sends information by appending variables to the end
of URL. The page and information is separated by a ‘?’ (question mark)
character. You can use PHP Get method ($_GET) to catch the sent data.
The URL would look like this in address bar after Submitting information by
using the Get method:
For example
http://www.yourdomain.com/index.htm?name=myname&age=30&location=
Pakistan
Following example shows using the PHP GET method with form’s get method.
PHP code:
<?php
if( $_GET["yourname"] || $_GET["yourage"] )
{
echo "Welcome ". $_GET['yourname']. "<br />";
echo "Your age is ". $_GET['yourage']. " years.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Your Name: <input type="text" name="yourname" />
Your Age: <input type="text" name="yourage" />
<input type="submit" />
</form>
</body>
</html>
PHP CODE OUTPUT
Your Name: Your Age: submit
After entering the name and age in the above example, when you click
the submit button, it will come back to the same page and display your
name and age. If you look at the address bar, you will see the following:
For example, if you entered the name as ‘ALI’ and age ’30’ while your
domain is “localhost” and page name is index.php then this is how the
address bar would look:
http://localhost/index.php?yourname=ALI&yourage=30
Following are the points to be noticed as using the Get in above
example:
In the HTML form, the method= ”GET” is used.
When receiving information at the server side, you have to use this:
PHP $_GET to get variable names sent by forms.
e.g. $_GET[‘yourname’]. You may assign this to a variable and save it to
database e.g. $name=$_GET[‘yourname’];
The HTML form data will be visible in the address bar as using the Get
method. Where “?” is used to separate from domain and variables are
separated by the “&” characters.
The amount of data that can be sent is limited in GET method. It is
about 2000 characters limit.
The GET method cannot send binary data.
As variables are visible in the address bar, this is visible to anyone
so considered as un-secure. This may be helpful in case you want to
offer bookmarking your site with non-sensitive data.
Get should not be used for sensitive information like passwords.
PHP $_GET is used to retrieve sent data along with using the form’s
get method.
The information sent by using the POST PHP method is not visible to
the users. The data sent by using post method of forms is received by
PHP POST method as shown below.
Following example shows using the PHP GET method with form’s get method.
PHP code:
<?php
if( $_POST["yourname"] || $_POST["yourage"] )
{
echo "Welcome ". $_POST['yourname']. "<br />";
echo "You age is ". $_POST['yourage']. " years.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Your Name: <input type="text" name="yourname" />
Your Age: <input type="text" name="yourage" />
<input type="submit" />
</form>
</body>
</html>
PHP CODE OUTPUT
Your Name: Your Age: submit
After entering the name and age in the above page, when you click
the submit button, it will come back to the same page and display
your name and age. You can see, the address bars will show just
the .phpfile name.
Following things should be noticed in the above example:
In the HTML form, the method=”POST” is used.
We used PHP $_POST to get the variable names sent by the form.
e.g. $_POST[‘yourname’].
Form variables will not be visible in the address bar, unlike the GET
method.
The amount of data that can be sent is not limited in the POST
method.
POST method can send binary data. So this method is used to
upload files like images, word document, pdfs, or other formats.
POST should be used for sensitive information like passwords etc.
Your users won’t be able to bookmark the page with submitted
information to be used in next visits as information is not visible.
You have to use the PHP Post method ($_POST) to retrieve the
information sent by web forms.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>form interface</title>
</head>
<body>
<form action="form.php"method="post">
name: <input type="text" name = "fname"><br>
age: <input type="text" name = "age"><br>
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form submission</title>
</head>
<body>Web form <br>
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “1234")
or die();
mysql_select_db ("vutest", $conn) or die( );
echo (" DB connected successfully");
$sql="INSERT INTO employee(NAME, AGE)
VALUES
('$_POST[fname]','$_POST[age]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "Record added successfully";
mysql_close($conn)
?>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form submission</title>
</head>
<body>Web form <br>
<?php
## Database Connection Include Web Site #
$conn = mysql_connect ("localhost", "root", “1234")
or die();
mysql_select_db ("vutest", $conn) or die( );
echo (" DB connected successfully");
$sql = 'SELECT ID, NAME, Age
FROM employee';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Id :{$row['ID']} <br> ".
"Name: {$row['NAME']} <br> ".
"AGE: {$row['Age']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Web Security, also known as “Cyber security” involves
protecting that information by preventing, detecting, and
responding to attacks
Web application security is the process of securing
confidential data stored online from unauthorized access
and modification.
Web browser (front end)
Web application (back end)
Prevent unauthorized users from accessing
sensitive data
◦ Authentication: identifying users to determine if they are
one of the authorized ones
◦ Access control: identifying which resources need
protection and who should have access to them
Prevent attackers from stealing data from network
during transmission
Web application security aims to address and fulfill the four conditions of security
Confidentiality: States that the sensitive data stored in the Web application
should not be exposed under any circumstances.
Integrity: States that the data contained in the Web application is consistent
and is not modified by an unauthorized user.
Availability: States that the Web application should be accessible to the
authentic user within a specified period of time depending on the request.
Nonrepudiation: States that the authentic user cannot deny modifying the data
contained in the Web application and that the Web application can prove its
identity to the authentic user.
The process of security analysis runs parallel with Web application
development. The group of programmers and developers who are responsible
for code development are also responsible for the execution of various
strategies, post-risk analysis, mitigation and monitoring.
There are two general approaches to the declarative
security for the Web application framework:
BASIC Authentication
Form-based Authentication
• By using declarative security, all you need to do is to put
the protected data in a directory
• The server will pop up a standard authentication window
asking for username & password upon user’s requests to
access restricted resources (specified directory or files).
Web server collects user identification information
via a customized login page, e.g.
| Basic | Form-based |
| Get username and password by using browser provided dialog box | Get username and password by using a customized login page |
| Only username and password can be collected | Customized data can be collected |
| HTTP Authentication header is used to convey username and password | Form data is used to convey username and password |
Web Application Security 8
Why would an attacker target my site?
Steal personal information, especially financial site
passwords
Read private data
◦ user names
◦ passwords
◦ credit card numbers
◦ prices
Change data
◦ prices of products
◦ passwords
Spoofing
A technique used to gain unauthorized access to
computers, whereby the intruder sends messages to a
computer with an IP address indicating that the message
is coming from a trusted host. To engage in IP spoofing,
a hacker must first use a variety of techniques to find an
IP address of a trusted host and then modify
the packet headers so that it appears that the packets
are coming from that host.
Newer routers and firewall arrangements can offer
protection against IP spoofing.
Damage or shut down the site
Spread viruses and other malware
Denial of Service (DoS):
Information Leakage
Man-in-the-Middle
Session Hijacking
SQL Injection
DOS Attack is a malicious attempt by a single
person or a group of people to cause the victim,
site or node to deny service to it customers.
Making a server unavailable by bombarding it
with requests.
DoS = when a single host attacks
DDoS = when multiple hosts attack
simultaneously
Purpose is to shut down a site, not penetrate it.
Modification of internal data, change of
programs
Information Leakage is an application weakness
where an application reveals sensitive data, such as
technical details of the web application,
environment, or user-specific data. Sensitive data
may be used by an attacker to exploit the target web
application, its hosting network, or its users.
Placing a malicious machine in the network and
using it to intercept traffic.
man-in-the-middle attack is an attack where the
attacker secretly relays and possibly alters the
communication between two parties who believe
they are directly communicating with each other
session hijacking, sometimes also known
as cookie hijacking is the exploitation of a
valid computer session—sometimes also called
asession key—to gain unauthorized access to
information or services in a computer system.
Stealing another user's session cookie to cover-up
as that user.
Inserting malicious SQL query code to reveal or
modify sensitive data.
An SQL Injection can destroy your database.
SQL injection is a technique where malicious
users can inject SQL commands into an SQL
statement, via web page input.
Injected SQL commands can alter SQL statement
and compromise the security of a web application.
Niche: A niche is a subset of a market that relates
to a specific topic.
When you are in a niche you are marketing a spec
ific product to a set audience to achieve greater su
ccess
Niche Website : A Website that Focuses on
Specific Information that is Both Useful and
Interesting for the Audience.
Online the word niche is used in a number of
technologies to refer to a specific topic, subject or
category.
Web sites and blogs may provide news and
content on a niche (e.g. a blog about sports or
finance), while online sellers often sell in niche
categories. It is believed that by focusing on a
niche topic or category you will see higher traffic
numbers for your Web site or blog-or see higher
profits in online selling-as you have less
competition in a niche area.
The words or phrases that members of a market
type into a search engine in order to explore a
particular niche. They are also known as search
queries.
The user may be searching keyword
1. For a website (navigational query)
2. To buy something (transactional query)
3. To earn something (informational query).
It is a practice search engine optimization (SEO)
professionals use to find and research actual
search terms that people enter into search
engines. Search engine optimization professionals
research keywords, which they use to achieve
better rankings in search engines. Once they find
a niche keyword, they expanded on it to find
similar keywords
Define Keyword List
Refine Keyword List
Competition and Keyword Relevance
Using Metrics to Choose Best Keywords
Integrating Keywords onto Your Site
Google AdWords Keyword planner
Google offers free tools to do some basic keyword
analysis. All the results are relevant only
for Google search engines. Features of AdWords
Keyword planner:
Get traffic estimates for the keyword.
Generate new keywords by combining different
keyword lists.
Create new keyword variations based on initial
keyword.
The process of maximizing the number of visitors
to a particular website by ensuring that the site
appears high on the list of results returned by a
search engine
It gives companies the ability to:
Drive high quality customers to their website
Increase sales leads from customers looking for
their products and services.
Build their brand online by communicating
marketing messages to their target audience.
Increase their profile against their competitors.
Target a global audience via international search
engines.
Be accountable with ROI tracking (SEM)
1. Discuss Business objectives.
2. Conduct initial keyword analysis.
3. Identify the keyword/landing page combinations.
4. Client Approval for Keyword/Landing Pages.
5. Baseline Ranking & Traffic reports.
6. On-site & Off-site optimization.
7. Detailed Recommendation documents.
8. Implementation.
9. Monitoring and Optimizing: We provide monthly reporting and
optimization recommendations. The reporting is compared to the
baseline (or previous month’s results) to identify trends and help
guide additional adjustments.
Keyword Ranking.
Website Traffic.
Increase in "Share of Traffic" per keyword.
Increased Revenue/keyword.
Lower dependence on Paid Search.
Lowering the cost per acquisition.
Content writing is a branch of content marketing,
which aims at writing in a way that draws the targeted
audience to the site in engaging them to active
participation. This participation may include readers
commenting on blogs and social networks, clicking
‘Like’ and ‘Share’ or ‘Tweet’ about the written post or
uploaded video.
Content visibility on the search engines like google
and yahoo, more and more writers are making use of
keywords, better known as search engine optimisation
(SEO) for search engine marketing (SEM) of their end
product
Backlinks are incoming links to a website or web
page.
The number of backlinks is one indication of the
popularity or importance of that website or page
Search engines often use the number of backlinks
that a website has as one of the most important
factors for determining that website's search
engine ranking, popularity and importance.
Backlinks and Forward links:
For example
Ø A and B are C’s backlinks
Ø C is A and B’s forward link
Comments
Post a Comment