0% found this document useful (0 votes)
2 views97 pages

HTML Material

The document provides an introduction to HTML and PHP, explaining their roles in web development. HTML is a markup language used for structuring web pages, while PHP is a server-side scripting language designed for creating dynamic content. It covers PHP's features, installation, syntax, and variable usage, emphasizing its open-source nature and compatibility with various platforms and databases.

Uploaded by

abrish2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views97 pages

HTML Material

The document provides an introduction to HTML and PHP, explaining their roles in web development. HTML is a markup language used for structuring web pages, while PHP is a server-side scripting language designed for creating dynamic content. It covers PHP's features, installation, syntax, and variable usage, emphasizing its open-source nature and compatibility with various platforms and databases.

Uploaded by

abrish2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PART ONE

1
HTML
HTML (Hyper Text Markup Language)
 is a markup language (markup -instructions for layout and style)
 is used to tell a Web browser
 where the heading is for a Web page,
 what is a paragraph,
 What is part of a table and so on, so it can structure
your document and render it properly.
 is not programming
Syntax:

2
Simpl
e page
<html>
<head>
<title> GuZo Ethiopia Travel and Tour PLC : About us </title>
</head>

<body>
<h1>About Guzo Ethiopia Travel and Tour PLC</h1>
<p>GuZo Ethiopia Travel and Tour PLC have been serving in
Ethiopia for the last three decades with honesty, great hospitality and
professional ethics. <p>
</body>
</html>

3
Looking at the code
<html>
<head>
<title> GuZo Ethiopia Travel
and Tour PLC : About us </title>
</head>

<body>
<h1>About Guzo Ethiopia
Travel and Tour PLC</h1>
<p>GuZo Ethiopia Travel and
Tour PLC have been serving in Ethiopia
for the last three decades with honesty,
great hospitality and professional ethics. 4
<p>
</body>
5
6
7
<body> . . . </body>
the body of the page, main
content
the information seen in the main
browser window

8
9
PART TWO

10
CHAPTER ONE
BASICS OF PHP
What You Should Already Know: Before you continue you should have a basic understanding
of the following:

 HTML/XHTML
 CSS
 JavaScript

1. INTRODUCTION TO PHP
PHP is a powerful server-side scripting language for creating dynamic and interactive
[Link] is the widely-used, free, and efficient alternative to competitors such as
Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded
directly into the HTML code.

The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web
server) on various operating systems. It also supports ISAPI and can be used with Microsoft's
IIS on Windows.

2. WHAT IS PHP?
The World Wide Web has changed very fast in so many ways. Sometimes it seems like
yesterday that a little known markup language with a strange name HTML (Hyper Text Markup
Language) was used by some physicists to link scientific documents at a group of CERN servers.
It was wondrous to read some text somewhere in the world with just a simple program, and what
is more information in the document could magically transport you to another one with related
information.

And this spread relatively quickly to other sciences. Text -only interfaces were the norm, and
simplicity of accessing information content the most important part of the equation. Text
documents with a small set of tags and a simple server setup was all you needed to inform your
colleagues and share the knowledge, independently of whether the organic chemist at the other
end was using his trusty Mac, or the theoretician was using her Unix box, or the impoverished
graduate was using a second or third hand PC running very flaky TCP/IP software.
11
Nowadays we expect more, much more than this. We expect a web site with lots of information,
and a good presentation, but we do not want to be distracted by a difficult interface. The
information should be easy to find, and it should be current. A clean and dynamic web site is a
great asset for the user and for the information provider. Long gone (fortunately) are the days of
garish -looking web sites with binky thingies, lots of animated images that usually were hiding a
shallow content depth. We want information, we want it 5 minutes ago and we want it in the
way we like it.

A modern web site is not just a web server; it also includes a way of storing data and querying
(a SQL database perhaps), a way of processing the requests from the user and creating
documents with the appropriate information. Many are the options open to the web developer,
but not all of them as open and general as others. We should not only consider the immediate
task at hand of creating a site with dynamic content, we need to be sure that we can still be
providing the said content independently of the changes in hardware or software technology.

We want to try and insure ourselves against future technology changes, dramatically reduce our
license costs, keep our hardware budget under control, and yet are portable to different web
servers and operating systems. We also want some assurance that we can do something about
that killer bug we just think we found in our web server or scripting environment, be able to
understand (if we want to)how the scripting works, and be able to modify the behavior of our
web server or scripting host to meet some particularly unusual need. Open source products will
be your best assurance that your application that works now in the "Super-Turbo Hexium IX"
machine of today, will work in the "Nanotech Cube Aleph" of tomorrow (I am exaggerating just
a wee bit).

12
3. FEATURES OF PHP
PHP (acronym for: PHP Hypertext Preprocessor), is a server-side embedded scripting language.
This means that it works within an HTML document to confer to it the capacity of generating
content on demand. You can convert your site into a web application, not just a collection of
static pages with information that may not get updated quite so often, which may be alright for a
"personal" web site (yes, we all have made such a beast), but not for one that is going to be used
for business or for education.

You may be asking "But, why PHP? There are so many other options like ASP, Cold
Fusion, Perl, Java, Python, even good old shell/awk/sed scripts?", and the answer will be:
simplicity, an almost natural way of using databases and platform independence.

And did I mention it was open source?

Of course general scripting or programming languages like Perl, Python, etc. have also
platform independence, and are open source. They are great languages, and sometimes
overkill for what you need, like using a concrete mixer to make scrambled eggs. PHP was
designed to work on the web, and in this ambit it excels; connecting and querying a database
is a simple task that can be handled in 2 or 3 lines of code. The PHP scripting engine is well
optimized for the response times needed on web applications; it can even be part of the web
server itself improving the throughput even more.

If it were only a matter of improving the speed of the scripts, then PHP will be one of
many solutions. But there is more to the PHP equation than that. There is the simplicity and
robustness of the language and the scripting engine. There is the connectivity to an ever
increasing number of database servers, the shorter development cycles and the ease
(encouraged by the syntaxes and constructs) of creating modular and reusable components.

You can perform tasks as simple as creating a feedback form that sends an e-mail to the
web maintainer, to a whole database driven document management system (like Midgard,
[Link] to helpdesk or bug tracking systems (like Keystone,
[Link] to a shopping cart application (like

13
FishCartSQL, [Link] to what would be considered "middle-ware"
packages without the need for extra languages or frameworks, and whole libraries for
quick and flexible development (PHPLIB, [Link]

Then there is the support from a widely distributed and cooperative community, with
several source repositories (like PHP Code Exchange, [Link] or Berber's
WeberDev [Link] many sites with tutorials (PHPBuilder,And did I
mention that it is open source?

There’s no more waiting until the next release for a feature to be added or a bug to get fixed.
Just take the source, make your modifications and there you are, instant customization and
complete control. No more guessing at whether a particular function or feature is insecure, the
code does not lie.

And who knows, maybe your modification gets to be so popular that others may want to use
it (hey! instant fame). And you cannot beat the total price for a development environment
using the combination of Linux, Apache, MySQL and PHP, not only cheaper than other more
proprietary environments, but also more stable and robust.

A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are executed
on the server.

14
4. WHERE TO START?
To get access to a web server with PHP support, you can:

 Install Apache (or IIS) on your own server, install PHP, and MySQL
 Or find a web hosting plan with PHP and MySQL support

What Do You Need?

 If your server supports PHP you don't need to do anything.


 Just create some .php files in your web directory, and the server will parse them for you.
Because it is free, most web hosts offer PHP support.
 However, if your server does not support PHP, you must install PHP.
 Here is a link to a good tutorial from [Link] on how to install PHP5:
[Link]

5. SETTING UP PHP WITH APACHE


PHP Installation

What Do You Need?


This Lecture will not explain how to install PHP, MySQL, or Apache Server. If your server
supports PHP - you don't need to do anything! You do not need to compile anything or install
any extra tools - just create some .php files in your web directory - and the server will parse them
for you. Most web hosts offer PHP support.

However, if your server does not support PHP, you must install PHP. Below is a link to a good
Lecture from [Link] on how to install PHP5: [Link]

DOWNLOAD PHP
Download PHP for free here: [Link]

Download MySQL Database

Download MySQL for free here:

[Link]

Download Apache Server

15
Download Apache for free here: [Link]

Testing Your XAMPP Installation


Follow these steps to test your XAMPP installation by launching the Apache web server
and creating a simple PHP file.

Step 1: In the XAMPP control panel, click on ‘Start’ under ‘Actions’ for the Apache
module. This instructs XAMPP to start the Apache web server.

Step 2: Open your web browser and type in: [Link] or [Link]

Step 3: Select your language from the splash screen.

Step 4: You should see the following screen. This means you’ve successfully installed
XAMPP on your computer.

Step 5: We will now test whether XAMPP has installed PHP successfully. To do this,
fire up Notepad and type the following into a new document:

16
<?php

echo ‘Hello world’;

?>

Save this file as ‘[Link]’ in c:\xampp\htdocs\ (or whichever directory you installed
XAMPP in).

Step 6: Navigate to localhost/[Link]. You should see the “Hello World” message:

6. BASIC PHP SYNTAX


You cannot view the PHP source code by selecting "View source" in the browser - you will only see the output from the
PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the
browser.

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.

On servers with shorthand support enabled you can start a scripting block with <? and end with ?
>.

However, for maximum compatibility, we recommend that you use the standard form (<?
php) rather than the shorthand form.

<?php

Some PHP code;


?>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.

There are two basic statements to output text with PHP: echo and print. Echo () and print() are
language constructs in PHP, both are used to output strings. The speed of both statements is
almost the same. Echo () can take multiple expressions where as print cannot take multiple
expressions. In the example above we have used the echo statement to output the text "Hello World".

17
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.

A PHP file normally contains HTML tags, just like an HTML file, and some PHP
scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:
There are two basic statements to output text with PHP: echo and print. In the example above
we have used the echo statement to output the text "Hello World".
<html>
<body>
<?php
echo "Hello World"; ?>
</body></html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from another.

7. COMMENTS IN PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

<html>
<body>
<?php
//This is a comment
/*This is a comment block
*/
?>
</body>
</html>

18
SUMMARY:

What is PHP?
 PHP stands for PHP: Hypertext Preprocessor
 PHP is a server-side scripting language, like ASP (Active Server Page)
 PHP scripts are executed on the server
 PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
 PHP is an open source software
 PHP is free to download and use
 PHP is a server-side scripting language.

What is a PHP File?

 PHP files can contain text, HTML tags and scripts


 PHP files are returned to the browser as plain HTML
 PHP files have a file extension of ".php", ".php3", or ".phtml"

Why PHP?

 PHP runs on different platforms (Windows, Linux, Unix, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS (Internet Information
Service), etc.)
 PHP is FREE to download from the official PHP resource: [Link]
 PHP is easy to learn and runs efficiently on the server side

19
CHAPTER TWO
PHP VARIABLES
1. VARIABLES: Variables are used for storing values, such as numbers, strings or
function results, so that they can be used many times in a script.
Variables in PHP
Variables are used for storing a value, like text strings, numbers or arrays. When a variable is
set it can be used over and over again in your script. All variables in PHP start with a $ sign
symbol. The correct way of setting a variable in PHP:

$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable. In that case it
will not [Link]'s try creating a variable with a string, and a variable with a number:

<?php

$txt = "Hello World!";

$number = 16;

?>

PHP is a Loosely Typed Language


In PHP a variable does not need to be declared before being set. In the example above,
you see that you do not have to tell PHP which data type the variable is. PHP automatically
converts the variable to the correct data type, depending on how they are set.

In a strongly typed programming language, you have to declare (define) the type and name of the
variable before using [Link] PHP the variable is declared automatically when you use it.

Variable Naming Rules


 A variable name must start with a letter or an underscore "_"
 A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9,
and _ )
 A variable name should not contain spaces. If a variable name is more than one word, it

20
should be separated with underscore ($my_string), or with capitalization ($myString)

2. PHP String
A string variable is used to store and manipulate a piece of text.
Strings in PHP
String variables are used for a value that contains character [Link] this Lecture we are
going to look at some of the most common functions and operators used to manipulate strings in
PHP. After we create a string we can manipulate it. A string can be used directly in a function or
it can be stored in a variable.

Below, the PHP script assigns the string "Hello World" to a string variable called $txt:

<?php

$txt="Hello World"; echo $txt;

?>

The output of the code above will be:

Hello World

Now, lets try to use some different functions and operators to manipulate our string.

PHP String Functions


The string functions allow you to manipulate strings.

The string functions are part of the PHP core. There is no installation needed to use these
functions.

Using the strlen() function


The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!":

<?php

21
echo strlen("Hello world!");
?>

The output of the code above will be:

12
The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string)

Using the strpos() function


The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no
match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>

The output of the code above will be:

6
As you see the position of the string "world" in our string is position 6. The reason that it is 6,
and not 7, is that the first position in the string is 0, and not 1.

The Concatenation Operator String


There is only one string operator in PHP. The concatenation operator (.) is used to put two string
values together. To concatenate two variables together, use the dot (.) operator:
<?php
$txt1="Hello World"; $txt2="1234";
echo $txt1 . " " . $txt2; ?>
The output of the code above will be:

Hello World 1234


22
If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to
separate the two variables.

3. PHP OPERATORS
Operators are used to operate on values. This section lists the different operators used in PHP.

Arithmetic Operators
Operator Description Example Result

+ Addition x=2 4

x+2

- Subtraction x=2 3

5-x

* Multiplication x=4 20

x*5

/ Division 15/5 3

5/2 2.5

% Modulus (division remainder) 5%2 1

10%8 2

10%2 0

++ Increment x=5 x=6

x++

-- Decrement x=5 x=4

x--

Assignment Operators

23
Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

Comparison Operators

Operator Description Example

== is equal to 5==8 returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true

Logical Operators
Operator Description Example

&& and x=6

y=3

(x < 10 && y > 1) returns true

|| or x=6

y=3

(x==5 || y==5) returns false

! not x=6

y=3

24
!(x==y) returns true

25
4. CONTROL STRUCTURES
I. SELECTIVE STATEMENTS

PHP If...Else Statements


The if, elseif and else statements in PHP are used to perform different actions based on different
conditions.
Conditional Statements
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.
 if...else statement - use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
 elseif statement - is used with the if...else statement to execute a set of code if one of
several condition are true
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false,
use the if....else statement.
Syntax

if (condition)

code to be executed if condition is true; else

code to be executed if condition is false;

Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>

26
<?php $d=date("D"); if ($d=="Fri")
echo "Have a nice weekend!"; else
echo "Have a nice day!";
?>
</body>
</html>

If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:
<html>
<body>
<?php $d=date("D"); if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!"; echo "See you on Monday!";
}
?>
</body>
</html>

The ElseIf Statement


If you want to execute some code if one of several conditions are true use the elseif
statement.

Syntax
if (condition)

code to be executed if condition is true;


elseif (condition)

27
code to be executed if condition is true;
else
code to be executed if condition is false;

Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<html>
<body>
<?php $d=date("D"); if ($d=="Fri")
echo "Have a nice weekend!"; elseif ($d=="Sun")
echo "Have a nice Sunday!"; else

echo "Have a nice day!";


?>
</body>
</html>

PHP Switch Statement


The Switch statement in PHP is used to perform one of several different actions based on one of
several different conditions.

If you want to select one of many blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else code.

Syntax
switch (expression)
{
case label1:
28
code to be executed if expression = label1; break;
case label2:
code to be executed if expression = label2; break;
default:
code to be executed
if expression is different from both label1 and label2;
}

Example
This is how it works:
 A single expression (most often a variable) is evaluated once
 The value of the expression is compared with the values for each case in the structure
 If there is a match, the code associated with that case is executed
 After a code is executed, break is used to stop the code from running into the next case
 The default statement is used if none of the cases are true
<html>
<body>
<?php switch ($x)
{
case 1:
echo "Number 1"; break;
case 2:
echo "Number 2"; break;
case 3:
echo "Number 3"; break;
default:
echo "No number between 1 and 3";
}
?>
29
</body>

</html>

II. PHP LOOPING STATEMENTS


Looping statements in PHP are used to execute the same block of code a specified number
of times.
Very often when you write code, you want the same block of code to run a number of times. You
can use looping statements in your code to perform this.
In PHP we have the following looping statements:
 while - loops through a block of code if and as long as a specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array
The while Statement
The while statement will execute a block of code as long a condition is true.
Syntax
While (condition) code to be executed;
Example
The following example demonstrates a loop that will continue to run as long as the variable i is
less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";

30
$i++;
}
?>
</body>
</html>

The do...while Statement


The do...while statement will execute a block of code at least once - it then will repeat the loop
as long as a condition is true.

Syntax
do
{
code to be executed;
}
while (condition);

Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 5:
<html>
<body>
<?php
$i=0;
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);

31
?>
</body>
</html>

The for Statement


The for statement is used when you know how many times you want to execute a statement or a
list of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Note: The for statement has three parameters. The first parameter initializes variables, the
second parameter holds the condition, and the third parameter contains the increments required
to implement the loop. If more than one variable is included in the initialization or the increment
parameter, they should be separated by commas. The condition must evaluate to true or false.
Example
The following example prints the text "Hello World!" five times:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>

32
6. PHP ARRAYS REFERENCES
An array can store one or more values in a single variable name.

Complete PHP String Reference


For a complete reference of all string functions, go to our complete PHP String Reference. The
reference contains a brief description and examples of use for each function
What is an array?

When working with PHP, sooner or later, you might want to create many similar variables.
Instead of having many similar variables, you can store the data as elements in an array. Each
element in the array has its own ID so that it can be easily accessed.

There are three different kind of arrays:

 Numeric array - An array with a numeric ID key

 Associative array - An array where each ID key is associated with a value

 Multidimensional array - An array containing one or more arrays

Numeric Arrays

A numeric array stores each element with a numeric ID key.

There are different ways to create a numeric array.

Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
Example 2
In this example we assign the ID key manually:
$names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";
The ID keys can be used in a script:
<?php

33
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?>
The code above will output:
Quagmire and Joe are Peter's neighbors
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.

Example 1
In this example we use an array to assign ages to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";

The ID keys can be used in a script:


<?php
$ages['Peter'] = "32"; $ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old."; ?>
The code above will output:

Peter is 32 years old.


Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
34
element in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array("Griffin"=>array ( "Peter", "Lois", "Morgan" ), "Quagmire"=>array ("Glenn"),
"Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output:
Array([Griffin] => Array(=> Peter=> Lois=> Morgan) [Quagmire] => Array ([0] => Glenn)
[Brown] => Array (=> Cleveland=> Loretta=> Junior ))
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
The code above will output:

Is Megan a part of the Griffin family?

The foreach Statement


The foreach statement is used to loop through arrays. For every loop, the value of the current
array element is assigned to $value (and the array pointer is moved by one) - so on the next loop,
you'll be looking at the next element.

Syntax

foreach (array as value)


{
code to be executed;
}
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php

35
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>

36
CHAPTER THREE

WORKING WITH PHP FUNCTIONS


The real power of PHP comes from its [Link] have user and built-in functions.

PHP user Functions

Function is a set of computer codes executed when that code is called. The main concept is how
to create your own functions. For a reference and examples of the built-in functions, please visit
our PHP Reference.

Create a PHP Function

A function is a block of code that can be executed whenever we need it.

Creating PHP functions:

 All functions start with the word "function()"

 Name the function - It should be possible to understand what the function does by its name.
The name can start with a letter or underscore (not a number)

 Add a "{" - The function code starts after the opening curly brace

 Insert the function code

 Add a "}" - The function is finished by a closing curly brace

Example

A simple function that writes my name when it is called:

<html>

<body>

<?php

37
function writeMyName()

echo "Kebede Mola";

writeMyName();

?>

</body>

</html>

Use a PHP Function

Now we will use the function in a PHP script:

<html>

<body>

<?php

function writeMyName()

echo " Kebede Mola ";

echo "Hello world!<br />";

echo "My name is ";


writeMyName();

echo ".<br />That's right, ";


writeMyName();

echo " is my name."; ?>

</body>

38
</html>

The output of the code above will be:

Hello world!

My name is Kebede Mola.

That's right, Kebede Mola is my name.

PHP Functions - Adding parameters

Our first function (writeMyName()) is a very simple function. It only writes a static string.

To add more functionality to a function, we can add parameters. A parameter is just like a
variable.

You may have noticed the parentheses after the function name, like: writeMyName(). The
parameters are specified inside the parentheses.

Example 1

The following example will write different first names, but the same last name:

<html>

<body>

<?php

function writeMyName($fname)

echo $fname . " Mola.<br />";

echo "My name is ";


writeMyName("Kebede ");

echo "My name is ";

39
writeMyName("Hege");

echo "My name is ";


writeMyName("Stale");

?>

</body>

</html>

The output of the code above will be:

My name is Kebede Mola.

My name is Hege Mola.

My name is Stale Mola.

Example 2

The following function has two parameters:

<html>

<body>

<?php

function writeMyName($fname,$punctuation)

echo $fname . " Mola" . $punctuation . "<br />";

echo "My name is ";


writeMyName("Kebede ",".");

echo "My name is ";


writeMyName("Hege","!");

40
echo "My name is ";
writeMyName("Ståle","...");

?>

</body>

</html>

The output of the code above will be:

My name is Kebede Mola.

My name is Hege Mola!

My name is Stale Mola...

PHP Functions - Return values

Functions can also be used to return values.

Example

<html>

<body>

<?php

function add($x,$y)

$total = $x + $y;
return $total;

echo "1 + 16 = " . add(1,16)፡

?>

41
</body>

</html>

The output of the code above will be:

1 + 16 = 17

In PHP - there are more than 700 built-in functions available.


Include File

Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will
be reused on multiple pages.

Server Side Includes

You can insert the content of a file into a PHP file before the server executes it, with the
include() or require() function. The two functions are identical in every way, except how they
handle errors. The include() function generates a warning (but the script will continue execution)
while the require() function generates a fatal error (and the script execution will stop after the
error).

These two functions are used to create functions, headers, footers, or elements that can be
reused on multiple pages.

This can save the developer a considerable amount of time. This means that you can
create a standard header or menu file that you want all your web pages to include. When the
header needs to be updated, you can only update this one include file, or when you add a new
page to your site, you can simply change the menu file (instead of updating the links on all web
pages).

The include() Function

42
The include() function takes all the text in a specified file and copies it into the file that uses
the include function.

Example 1

Assume that you have a standard header file, called "[Link]". To include the header file
in a page, use the include() function, like this:

<html>

<body>

<?php include("[Link]"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>

</html>

Example 2

Now, let's assume we have a standard menu file that should be used on all pages (include

files usually have a ".php" extension). Look at the "[Link]" file below:

<html>

<body>

<a href="[Link] <a

href="[Link] Us</a>

<a href="[Link] Us</a>

The three files, "[Link]", "[Link]", and "[Link]" should all include the

"[Link]" file. Here is the code in "[Link]":

43
<?php include("[Link]"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>

</html>

If you look at the source code of the "[Link]" in a browser, it will look something like

this:<html>

<body>

<a href="[Link]">Home</a>

<a href="[Link]">About Us</a>

<a href="[Link]">Contact Us</a>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>

</html>

And, of course, we would have to do the same thing for "[Link]" and "[Link]". By
using include files, you simply have to update the text in the "[Link]" file if you decide to
rename or change the order of the links or add another web page to the site.

The require() Function

The require() function is identical to include(), they only handle errors differently. The include
() function generates a warning (but the script will continue execution) while the require ()
function generates a fatal error (and the script execution will stop after the error).

If you include a file with the include() function and an error occurs, you might get an error
44
message like the one below.

PHP code:

<html>

<body>

<?php

include("[Link]");

echo "Hello World!";

?>

</body>

</html>

Error message:

Warning: include([Link]) [[Link]]: failed to open


stream:

No such file or directory in C:\home\website\[Link] on line 5 Warning:


include() [[Link]]:

Failed opening '[Link]' for inclusion (include_path='.;C:\php5\pear')in C:\home\website\


[Link] on line 5

Hello World!

Notice that the echo statement is still executed! This is because a Warning does not stop the
script execution.

Now, let's run the same example with the require() function.

45
PHP code:

<html>

<body>

<?php

require("[Link]");
echo "Hello World!";

?>

</body>

</html>

Error message:

Warning: require([Link]) [[Link]]:

failed to open stream:

No such file or directory in C:\home\website\[Link] on line 5 Fatal error: require()


[[Link]]:

Failed opening required '[Link]' (include_path='.;C:\php5\pear')

in C:\home\website\[Link] on line 5

The echo statement was not executed because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should
not continue executing if files are missing or misnamed.

PHP Date () Function

The PHP date() function is used to format a time or a date. The PHP date() function formats a
timestamp to a more readable date and time.

46
Syntax

date(format,timestamp)

Parameter Description

format Required. Specifies the format of the timestamp

Optional.
timestampSpecifies a timestamp. Default is the current date and time (as a

timestamp)

PHP Date - What is a Timestamp?

A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also
known as the Unix Timestamp.

PHP Date - Format the Date

The first parameter in the date () function specifies how to format the date/time. It uses letters
to represent date and time formats. Here are some of the letters that can be used:

 d - The day of the month (01-31)

 m - The current month, as a number (01-12)

 Y - The current year in four digits

An overview of all the letters that can be used in the format parameter can be found in our
PHP Date reference.

Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:

47
<?php

date_default_timezone_set('UTC');

echo date("Y/m/d");

echo "<br />";

echo date("Y.m.d");

echo "<br />";

echo date("Y-m-d");

?>

The output of the code above could be something like this:

2006/07/11

2006.07.11

2006-07-11

PHP Date - Adding a Timestamp

The second parameter in the date() function specifies a timestamp. This parameter is optional.

If you do not supply a timestamp, the current time will be used.

In our next example we will use the mktime() function to create a timestamp for tomorrow.

The mktime() function returns the Unix timestamp for a specified date.

48
Syntax

mktime(hour,minute,second,month,day,year,is_dst)

To go one day in the future we simply add one to the day argument of mktime():

<?php

date_default_timezone_set('UTC');

$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));

echo "Tomorrow is ".date("Y/m/d", $tomorrow);

?>

The output of the code above could be something like this:

Tomorrow is 2006/07/12

49
CHAPTER FOUR

PHP FORMS AND USER INPUT

The PHP $_GET and $_POST variables are used to retrieve information from forms,
like user input.

PHP Form Handling: The most important thing to notice when dealing with HTML forms and PHP
is that any form element in an HTML page will automatically be available to your PHP scripts.

For example:
<html>
<body>
<form action="[Link]" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The example HTML page above contains two input fields and a submit button. When the user
fills in this form and click on the submit button, the form data is sent to the "[Link]" file.

The "[Link]" file looks like this:

<html>

<body>

Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old.

</body>

</html>

50
A sample output of the above script may be:

Welcome John.

You are 28 years old.

Form Validation

User input should be validated whenever possible. Client side validation is faster, and will
reduce server load.

However, any site that gets enough traffic to worry about server resources may also need to
worry about site security. You should always use server side validation if the form accesses a
database.

A good way to validate a form on the server is to post the form to itself, instead of jumping to a
different page. The user will then get the error messages on the same page as the form. This
makes it easier to discover the error.

PHP $_GET: The $_GET variable is used to collect values from a form with method="get".

The $_GET Variable

The $_GET variable is an array of variable names and values sent by the HTTP GET method.

The $_GET variable is used to collect values from a form with method="get". Information sent
from a form with the GET method is visible to everyone (it will be displayed in the browser's
address bar) and it has limits on the amount of information to send (max. 100 characters).

Example

<form action="[Link]" method="get">

Name: <input type="text" name="name" />

Age: <input type="text" name="age" />

<input type="submit" />

</form>

51
When the user clicks the "Submit" button, the URL sent could look something like this:

[Link]
<?name=Peter&age=37

The "[Link]" file can now use the $_GET variable to catch the form data (notice that
the names of the form fields will automatically be the ID keys in the $_GET array):

Welcome <?php echo $_GET["name"]; ?>.<br />

You are <?php echo $_GET["age"]; ?> years old!

Why use $_GET?

Note: When using the $_GET variable all variable names and values are displayed in the
URL. So this method should not be used when sending passwords or other sensitive
information! However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.

Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed
100 characters.

Using GET or POST

$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.

The $_REQUEST Variable

52
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.

Example

Welcome <?php echo $_REQUEST["name"]; ?>.<br />

You are <?php echo $_REQUEST["age"]; ?> years old!

PHP $_POST

The $_POST variable is used to collect values from a form with method="post".

The $_POST Variable

The $_POST variable is an array of variable names and values sent by the HTTP POST method.

The $_POST variable is used to collect values from a form with method="post". Information
sent from a form with the POST method is invisible to others and has no limits on the amount
of information to send.

Example

<form action="[Link]" method="post">

Enter your name: <input type="text" name="name" />

Enter your age: <input type="text" name="age" />

<input type="submit" />

</form>

When the user clicks the "Submit" button, the URL will not contain any form data, and will
look something like this:

[Link]

The "[Link]" file can now use the $_POST variable to catch the form data (notice that
the names of the form fields will automatically be the ID keys in the $_POST array):

53
Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old!

Why use $_POST?

 Variables sent with HTTP POST are not shown in the URL

 Variables have no length limit

However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.

The $_REQUEST Variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.

Example

Welcome <?php echo $_REQUEST["name"]; ?>.<br />

You are <?php echo $_REQUEST["age"]; ?> years old!

CREATE UPLOAD FILES AND PICTURES

With PHP, it is possible to upload files and pictures to the server.

Create an Upload-File Form

To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files:

<html>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">

54
<label for="file">Filename:</label>

<input type="file" name="file" id="file" />


<br />

<input type="submit" name="submit" value="Submit"


/>

</form>

</body>

</html>

Notice the following about the HTML form above:

 The enctype attribute of the <form> tag specifies which content-type to use when
submitting the form. "multipart/form-data" is used when a form requires binary data,
like the contents of a file, to be uploaded

 The type="file" attribute of the <input> tag specifies that the input should be processed as
a file. For example, when viewed in a browser, there will be a browse-button next to the
input field.

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.

Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:

<?php

if ($_FILES["file"]["error"] > 0)

echo "Error: " . $_FILES["file"]["error"] . "<br />";

else

55
{

echo "Upload: " . $_FILES["file"]["name"] . "<br />";


echo "Type: " . $_FILES["file"]["type"] . "<br />";

echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

echo "Stored in: " . $_FILES["file"]["tmp_name"];

?>

By using the global PHP $_FILES array you can upload files from a client computer to the
remote server.

The first parameter is the form's input name and the second index can be either "name",
"type", "size", "tmp_name" or "error".

Like this:

 $_FILES["file"]["name"] - the name of the uploaded file

 $_FILES["file"]["type"] - the type of the uploaded file

 $_FILES["file"]["size"] - the size in bytes of the uploaded file

 $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server

 $_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions
on what the user is allowed to upload.

Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg
files and the file size must be under 20 kb:

<?php

if((($_FILES["file"]["type"]=="image/gif")|| ($_FILES["file"]["type"] == "image/pjpeg")) &&

56
($_FILES["file"]["size"] < 20000))

if ($_FILES["file"]["error"] > 0)

echo "Error: " . $_FILES["file"]["error"] . "<br />";

else

echo "Upload: " . $_FILES["file"]["name"] . "<br />";

echo "Type: " . $_FILES["file"]["type"] . "<br />";

echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

echo "Stored in: " . $_FILES["file"]["tmp_name"];

else

echo "Invalid file";

?>

Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on
the server.

The temporary copied files disappear when the script ends. To store the uploaded file we need
to copy it to a different location:

57
<? Php

if(($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] ==


"image/pjpeg") && ($_FILES["file"]["size"] < 20000))

if ($_FILES["file"]["error"] > 0)

echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

else

echo "Upload: " . $_FILES["file"]["name"] . "<br />";


echo "Type: " . $_FILES["file"]["type"] . "<br />";

echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("upload/" . $_FILES["file"]["name"]))

echo $_FILES["file"]["name"] . " already exists. ";

else

move_uploaded_file($_FILES["file"]
["tmp_name"], "upload/" . $_FILES["file"]
["name"]);

echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

58
}}}

else

echo "Invalid file";

}?>

The script above checks if the file already exists, if it does not, it copies the file to
the specified folder i.e. this example saves the file to a new folder called "upload".

59
CHAPTER FIVE

PHP COOKIES AND SESSIONS

5.1. WHAT IS A COOKIE?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will
send the cookie too. With PHP, you can both create and retrieve cookie values.

A. How to Create and use a Cookies?

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax: setcookie(name, value, expire, path, domain);

Example

In the example below, we will create a cookie named "user" and assign the value "Alex Porter"
to it. We also specify that the cookie should expire after one hour:

<?php setcookie("user", "Alex Porter", time()+3600); ?>

<html>

<body>

<?php

Some code;

?>

</body>

</html>

60
Note: The value of the cookie is automatically URL encoded when sending the cookie, and
automatically decoded when received (to prevent URL encoding, use setrawcookie() instead).

B. How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?php

// Print a cookie

echo $_COOKIE["user"];

// A way to view all cookies

print_r($_COOKIE);

?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>

<body>

<?php

if (isset($_COOKIE["user"]))

echo "Welcome " . $_COOKIE["user"] . "!<br />";

else

echo "Welcome guest!<br />";

?>

</body>

</html>

61
62
C. . How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php

// set the expiration date to one hour ago

setcookie("user", "Alex", time()-3600);

?>

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to pass
the data through forms (forms and user input are described earlier in this Lecture).

The form below passes the user input to "[Link]" when the user clicks on the "Submit"
button:

<html>

<body>

<form action="[Link]" method="post">

Name: <input type="text" name="name" />

Age: <input type="number" name="age" />

<input type="submit" />

</form>

</body>

</html>

63
Retrieve the values in the "[Link]" file like this:

<html>

<body>

Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old.

</body>

</html>

5.2. PHP SESSIONS

A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.

A. PHP Session Variables

When you are working 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 and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may want
to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this
UID. The UID is either stored in a cookie or is propagated in the URL.

64
B. CREATE, USE AND DELETE SESSION

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

<?php
session_start(); ?>

<html>

<body>

<?php

Some code;

?>

</body>

</html>

The code above will register the user's session with the server, allow you to start saving
user information, and assign a UID for that user's session.

C. Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start();

// store session data


$_SESSION['views']
=1; ?>

65
<html>

<body>

<?php

//retrieve session data

echo "Pageviews=".
$_SESSION['views']; ?>

</body>

</html>

Output:

Pageviews=1

In the example below, we create a simple page-views counter. The isset() function checks if
the "views" variable has already been set. If "views" has been set, we can increment our
counter. If "views" doesn't exist, we create a "views" variable and set it to 1:

<?php

session_start();
if(isset($_SESSION['views']))

$_SESSION['views']=$_SESSION['views']+1;

else
$_SESSION['views']=1;

echo "Views=". $_SESSION['views']; ?>

66
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()

function. The unset() function is used to free the specified session variable:

<?php

unset($_SESSION['views']);

?>

You can also completely destroy the session by calling the session_destroy() function:

<?php

session_destroy();

?>

67
CHAPTER SIX
PHP DATA BASE MANIPULATIONS
6.1. INTRODUCTION
MySQL is the most popular open source database server.
Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can download
MySQL for free here: [Link]
Facts About MySQL Database
One great thing about MySQL is that it can be scaled down to support embedded
database applications. Perhaps it is because of this reputation that many people
believe that MySQL can only handle small to medium-sized systems.
The truth is that MySQL is the de-facto standard database for web sites that
support huge volumes of both data and end users (like Fraudster, Yahoo, Google).
Look at [Link] for an overview of companies that
use MySQL.
What is MySQL?
MySQL is a database. A database defines a structure for storing information. In a
database, there are tables. Just like HTML tables, database tables contain rows,
columns, and cells. Databases are useful when storing information categorically. A
company may have a database with the following tables: "Employees", "Products",
"Customers" and "Orders".
Database Tables
A database most often contains one or more tables. Each table has a name (e.g.
"Customers" or "Orders"). Each table contains records (rows) with data.
Below is an example of a table called "Persons":

68
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).

6.2. PHP MySQL Connect to a Database


The free MySQL Database is very often used with PHP. Before you can access
and work with data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.

Syntax

mysql_connect(servername,username,password);

Parameter Description
Optional. Specifies the server to connect to. Default value is
servername "localhost:3306"
Optional. Specifies the username to log in with. Default value
username is the name of the
user that owns the server process
password Optional. Specifies the password to log in with. Default is ""

Note: There are more available parameters, but the ones listed above are the most

69
important. Visit our full PHP MySQL Reference for more details.
Example
In the following example we store the connection in a variable ($con) for later use
in the script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123"); if
(!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code ?>

CLOSING A CONNECTION
The connection will be closed as soon as the script ends. To close the
connection before, use the mysql_close() function.
<?php
$con = mysql_connect("localhost","peter","abc123"); if
(!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
6.3. QUERIES
A query is a question or a request. With MySQL, we can query a database for
specific information and have a recordset returned. Look at the following query:

70
SELECT LastName FROM Persons;
The query above selects all the data in the LastName column in the Persons table,
and will return a recordset like this:

LastName
Hansen
Svendson
Pettersen

6.4. PHP MySQL Create Database and Tables


A database holds one or multiple tables.
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.

Example
In the following example we create a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!
$con)
{

71
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con); ?>
Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.
Syntax
CREATE TABLE table_name
(column_name1 data_type, column_name2 data_type, column_name3 data_type,
....... )

We must add the CREATE TABLE statement to the mysql_query() function to


execute the command.
Example
The following example shows how you can create a table named "person", with
three columns. The column names will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123"); if
(!$con)

72
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table in my_db database


mysql_select_db("my_db", $con); $sql = "CREATE TABLE person (FirstName
varchar(15),LastName varchar(15), Age int )"; mysql_query($sql,$con);
mysql_close($con);
?>
Important: A database must be selected before a table can be created. The
database is selected with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the
maximum length of the field, e.g. varchar(15).
MySQL Data Types
Below is the different MySQL data types that can be used:
Numeric Data Types Description
int(size) Hold integers only. The maximum number of

73
digits can be
smallint(size) specified in the size parameter
tinyint(size)
mediumint(size)
bigint(size)
Hold numbers with fractions. The maximum
decimal(size,d) number of
digits can be specified in the size parameter.
double(size,d) The maximum
number of digits to the right of the decimal is
float(size,d) specified in
the d parameter

Textual Data Types Description


Holds a fixed length string (can contain
char(size) letters, numbers,
and special characters). The fixed size is
specified in
parenthesis
Holds a variable length string (can contain
varchar(size) letters, numbers,
and special characters). The maximum size is
specified in
parenthesis
Holds a variable string with a maximum
Tinytext length of 255

74
characters
Holds a variable string with a maximum
Text length of 65535
Blob characters
Holds a variable string with a maximum
Mediumtext length of 16777215
Mediumblob characters
Holds a variable string with a maximum
Longtext length of
Longblob 4294967295 characters

Date Data Types Description


date(yyyy-mm-dd) Holds date and/or time
datetime(yyyy-mm-dd
hh:mm:ss)
timestamp(yyyymmddhhmms
s)
time(hh:mm:ss)

Misc. Data Types Description


ENUM is short for ENUMERATED list. Can
enum(value1,value2,ect) store one of up to
65535 values listed within the ( ) brackets. If
a value is
inserted that is not in the list, a blank value
will be inserted
Set SET is similar to ENUM. However, SET can

75
have up to 64
list items and can store more than one choice

Primary Keys and Auto Increment Fields


Each table should have a primary key field.
A primary key is used to uniquely identify the rows in a table. Each primary
key value must be unique within the table. Furthermore, the primary key field
cannot be null because the database engine requires a value to locate the
record.
The primary key field is always indexed. There is no exception to this rule!
You must index the primary key field so the database engine can quickly
locate rows based on the key's value.
The following example sets the personID field as the primary key field. The
primary key field is often an ID number, and is often used with the
AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the
value of the field by 1 each time a new record is added. To ensure that the
primary key field cannot be null, we must add the NOT NULL setting to the
field.

Example
$sql = "CREATE TABLE person (personID int NOT NULL
AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15),
LastName varchar(15), Age int )";
mysql_query($sql,$con);

PHP MySQL Insert Into

76
The INSERT INTO statement is used to insert new records into a database table.
Insert Data into a Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
INSERT INTO table_name VALUES (value1, value2,....)
You can also specify the columns where you want to insert the data:

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2 ...)

Note: SQL statements are not case sensitive. INSERT INTO is the same as insert
into.
To get PHP to execute the statements above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.

Example
In the previous chapter we created a table named "Person", with three columns;
"Firstname", "Lastname" and "Age". We will use the same table in this example.
The following example adds two new records to the "Person" table:
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!
$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO person (FirstName, LastName, Age) VALUES

77
('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO person (FirstName, LastName,
Age) VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con); ?>
Insert Data From a Form Into a Database
Now we will create an HTML form that can be used to add new records to the
"Person" table.
Here is the HTML form:

<html>

<body>

<form action="[Link]" method="post">


Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

When a user clicks the submit button in the HTML form in the example above, the
form data is sent to "[Link]". The "[Link]" file connects to a database, and
retrieves the values from the form with the PHP $_POST variables. Then, the
mysql_query() function executes the INSERT INTO statement, and a new record
will be added to the database table.

78
Below is the code in the "[Link]" page:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)

die('Could not connect: ' . mysql_error());


}
mysql_select_db("my_db", $con);
$sql="INSERT INTO person (FirstName, LastName, Age) VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());

echo "1 record added";


mysql_close($con)
?>

PHP MySQL Select


The SELECT statement is used to select data from a database.
Select Data From a Database Table
The SELECT statement is used to select data from a database.

79
Syntax
SELECT column_name(s) FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as select. To get
PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example selects all the data stored in the "Person" table (The *
character selects all of the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
The example above stores the data returned by the mysql_query() function in the
$result variable. Next, we use the mysql_fetch_array() function to return the first

80
row from the record set as an array. Each subsequent call to mysql_fetch_array()
returns the next row in the record set. The while loop loops through all the records
in the recordset. To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).

The output of the code above will be:

Peter Griffin
Glenn Quagmire

Display the Result in an HTML Table


The following example selects the same data as the example above, but will
display the data in an HTML table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
81
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
Echo"</table>";
mysql_close($con); ?>
The output of the code above will be:

Firstname Lastname

Quagmi
Glenn re

Peter Griffin

PHP MySQL the Where Clause


To select only data that matches a specified criteria, add a WHERE clause to the
SELECT statement.
The WHERE clause
To select only data that matches a specific criteria, add a WHERE clause to the
SELECT statement.
Syntax
SELECT column FROM table WHERE column operator value

82
The following operators can be used with the WHERE clause:
Operator Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern

Note: SQL statements are not case sensitive. WHERE is the same as where.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example will select all rows from the "Person" table, where
FirstName='Peter':
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM

83
person WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
The output of the code above will be:
Peter Griffin

PHP MySQL Order By Keyword


The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY Keyword
The ORDER BY keyword is used to sort the data in a recordset.
Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name
Note: SQL statements are not case sensitive. ORDER BY is the same as order by.
Example
The following example selects all the data stored in the "Person" table, and sorts
the result by the "Age" column:
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!
$con)
{
die('Could not connect: ' . mysql_error());
}

84
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con); ?>
The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Sort Ascending or Descending


If you use the ORDER BY keyword, the sort-order of the recordset is ascending by
default (1 before 9 and "a" before "p").
Use the DESC keyword to specify a descending sort-order (9 before 1 and "p"
before "a"):
SELECT column_name(s) FROM table_name ORDER BY column_name DESC
Order by Two Columns
It is possible to order by more than one column. When ordering by more than one
column, the second column is only used if the values in the first column are
identical:
SELECT column_name(s) FROM table_name ORDER BY column_name1,
column_name2
85
PHP MySQL Update
The UPDATE statement is used to modify data in a database table.
Update Data In a Database: The UPDATE statement is used to modify data in a
database table.

Syntax
UPDATE table_name SET column_name = new_value WHERE column_name =
some_value;
Note: SQL statements are not case sensitive. UPDATE is the same as update.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.

Example
Earlier in the Lecture we created a table named "Person". Here is how it looks:

FirstName LastName Age


Peter Griffin 35
Glenn Quagmire 33
The following example updates some data in the "Person" table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{

86
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Person SET Age = '36' WHERE FirstName = 'Peter'
AND LastName = 'Griffin'"); mysql_close($con);
?>
After the update, the "Person" table will look like this:
FirstName LastName Age
Peter Griffin 36
Glenn Quagmire 33
PHP MySQL Delete From
The DELETE FROM statement is used to delete rows from a database table.
Delete Data In a Database
The DELETE FROM statement is used to delete records from a database table.

Syntax
DELETE FROM table_name WHERE column_name = some_value
Note: SQL statements are not case sensitive. DELETE FROM is the same as
delete from.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.

Example
Earlier in the Lecture we created a table named "Person". Here is how it looks:
FirstName LastName Age

87
Peter Griffin 35
Glenn Quagmire 33

The following example deletes all the records in the "Person" table where
LastName='Griffin':
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Person WHERE
LastName='Griffin'"); mysql_close($con);
?>
After the deletion, the table will look like this:

FirstName LastName Age


Glenn Quagmire 33

88
SUMMARIZED NOTE AND LAB MANUAL

PHP DATA BASE

The data in MYSQL is stored in database object called tables. A table is a collection of related
data entries and it consists of columns and rows. Databases are useful when storing information
categorically. A company may have a database.

We can manage our MYSQL database server using a management tool called phpmyadmin. This
tool helps us to create our database and manage our database simply.

Now let us see how we interact with our MYSQL database using our php script. There are four
steps involved that we have to follow in order to talk to database, and they are listed as follows:

1. Connect to the database server using MYSQL user account :-

To connect to the MYSQL database server we need to use the mysql_connect () function. This
takes the following parameters:

 Database server location (URL)


 Database server Username
 Database server password corresponding username.

2. Select A Database To Use:-

To select a database we use php built-in function mysql_select (). This function takes two
parameters:

 Database name and


 mysql connect
3. Build and Execute Query (CRUD Operations):-

To execute queries we use yet another built –in PHP function called mysql_query (). This
function takes a query as a parameter and returns a result set.

4. Close connection :-

89
Since leaving the connection open when we are not using the database leads to security
issues, we need to close the connection after we are done using it by the function:
mysql_close ($connection);

Now let us look at an example that demonstrates the above definitions. We will assume we
have database server at localhost with user name root and password and we have a database
called WKU and this database has table called users and have two attributes username and
password.

What we will build a PHP script that add user


[Link]
<html>
<head>
<title>Add user </title>
</head>
<body>
<form action="[Link]" method="post">
Use Name: <input type="text" name="uname" />
PASSWORD: <input type="password" name="pass" />
<input type="submit" name="adduser" value="Adduser" />
</form>
</body>
</html>
<?php
if(isset($_POST["adduser"]))
$username=$_POST["uname"];
$pass=$_POST["pass"];
// Database constants
define("DB_SERVER" ,"localhost");
define("DB_USER" ,"root");

90
define("DB_PASS" ," ");
define("DB_NAME" ,"WKU");
//1. create database connection

$connnection=mysql_connect("DB_SERVER","DB_USER","DB_PASS");
if (!$connection)
{
die("Database connection failed: " . mysql_error());
}
//2. select a database to use
$db_select = mysql_connect_db("DB_NAME",$connection);
if (!db_select)
{
die('database selection failed: ' . mysql_error());
}

//3. build Query


$query="Insert into user";
$query=."values({$username},{$pass})";

//4. Execute Query


$result=mysql_query($query);
if(!$result){
die("Adding user is Failed".mysql_error());
}
else
{
echo "New user added successfully";
//5. Closing a Connection
mysql_close($connection);?>

91
[Link]
<?php
//creating connection to database
$conn=mysql_connect("localhost","root","");
//selecting the database wku
mysql_select_db("wku",$conn);
//database query to retrieve all IDs form student table
$q1="select ID from student";
//query the database and assign it to variable result
$res=mysql_query($q1,$conn);
//creating a search form
echo"<form action='".$_SERVER['PHP_SELF']."' method=\"post\">";
echo"<select name=\"sel\">";
//fetching the result
while($row=mysql_fetch_row($res))
{
echo "<option value=\"$row[0]\">".$row[0]."</option>";
}
//closing the form and select tag
echo"</select>";
echo"<input type='submit' name='search' value='search'>
</form>";
//creating a check for wheather we click search or not
if(isset($_POST['search']))
{
//recieving value form select drop down option using POST
$id=$_POST['sel'];
//query for retrieving all values that match the ID that we choose from the dropdown
$q2="select * from students where ID='$id'";
$res2=mysql_query($q2,$conn);

92
//creating a form for Insert and delete
echo"<form action='".$_SERVER['PHP_SELF']."'method=\"post\">";
//retrieving and displaying all values using textbox
while($row1=mysql_fetch_array($res2))
{
echo" Student ID <input type='text' name='ID' value='".$row1['ID']."'> <br>";
echo"First Name:<input type='text' name='fname' value='".$row1['fName']."'>";
echo"</br>Last Name:<input type='text' name='Lname' value='".$row1['Lname']."'>";
echo"</br>Dep :<input type='text' name='dep' value='".$row1['dep']."'>";
}
echo"<br> <input type='submit' name='Insert' value='Insert'>
<input type='submit' name='delete' value='Delete'></form>";
}
//check
if(isset($_POST['Insert']))
{
$id=$_POST['ID'];
$fname=$_POST['fname'];
$lname=$_POST['Lname'];
$dep=$_POST['dep'];
//query statment for Insert
$q3="Insert into students values('$fname','$lname','$dep','$id')";
$res3=mysql_query($q3,$conn);
if(!$res3)
die("query error ".mysql_error());
echo"you query successfully!!!!";
}
if(isset($_POST['delete']))
{
$id=$_POST['ID'];

93
$name=$_POST['fname'];
//query statment for delete
$q4="delete from students where ID='$id'";
$res4=mysql_query($q4,$conn);
if(!$res4) die("query error ".mysql_error());
echo"you have erased user".$fname." !!!!";
}
?>

[Link]

<?php
//creating connection to database
$conn=mysql_connect("localhost","root","");
//selecting the database wku
mysql_select_db("wku",$conn);
//database query to retrieve all IDs form student table
$q1="select ID from student";
//query the database and assign it to variable result
$res=mysql_query($q1,$conn);
//creating a search form
echo"<form action='".$_SERVER['PHP_SELF']."' method=\"post\">";
echo"<select name=\"sel\">";
//fetching the result
while($row=mysql_fetch_row($res))
{
echo "<option value=\"$row[0]\">".$row[0]."</option>";
}
//closing the form and select tag
echo"</select>";

94
echo"<input type='submit' name='search' value='search'></form>";
//creating a check for wheather we click search or not
if(isset($_POST['search']))
{
//recieving value form select drop down option using POST
$id=$_POST['sel'];
//query for retrieving all values
//that match the ID that we choose from the dropdown
$q2="select * from students where ID='$id'";
$res2=mysql_query($q2,$conn);
//creating a form for update and delete
echo"<form action='".$_SERVER['PHP_SELF']."'method=\"post\">";
//retrieving and displaying all values using textbox
while($row1=mysql_fetch_array($res2))
{
echo"<input type='hidden' name='ID' value='".$row1['ID']."'>";
echo"First Name:<input type='text' name='fname' value='".$row1['fName']."'>";
echo"</br>Last Name:<input type='text' name='Lname' value='".$row1['Lname']."'>";
echo"</br>Dep :<input type='text' name='dep' value='".$row1['dep']."'>";
}
echo"</br>Click to update:<input type='submit' name='update' value='update'>
</br>click to Delete:<input type='submit' name='delete' value='Delete'></form>";
}
//check
if(isset($_POST['update']))
{
$id=$_POST['ID'];
$fname=$_POST['fname'];
$lname=$_POST['Lname'];
$depid=$_POST['dep'];

95
//query statment for update
$q3="update students set fName='$fname',Lname='$lname',dep='$dep' where ID='$id'";
$res3=mysql_query($q3,$conn);
if(!$res3)
die("query error ".mysql_error());
echo"you updated successfully!!!!";
}
if(isset($_POST['delete']))
{
$id=$_POST['ID'];
$name=$_POST['fname'];
//query statment for delete
$q4="delete from students where ID='$id'";
$res4=mysql_query($q4,$conn);
if(!$res4)
die("query error ".mysql_error());
echo"you have erased user".$fname." !!!!";
}
?>

96
ACTIVITY
1. Create a table named Borrowed_Books under the ‘wku’ database with attributes
Student_ID, Book_ID, Book_Title, Author, Publisher and Borrowed_date. The Student_ID in
this table is a foreign key which refers to the ID in student table. (assume one book is
borrowed by one student, but 1 student can borrow many books)

2. Create a form that inserts all the borrowed books to this table(insert at least 6 records).
Student_ID should be inserted in the Address table only if it does exist in the Student table.

3. Create a script that retrieves all the students that borrowed books and another one which
retrieves only male students that borrowed books.

4. Create another script that retrieves all students that borrowed more than one books.

5. Create a script that updates and deletes records.

97

You might also like