0% found this document useful (0 votes)
66 views83 pages

Web Desing, Programmig and Administration

Web design notes

Uploaded by

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

Web Desing, Programmig and Administration

Web design notes

Uploaded by

ellen deus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

COURSE: WEB DESIGN, PROGRAMMING AND ADMINISTRATION

COURSE CODE:

LECTURER: MR ARAKA GEOFFREY

BCS&BIT 2.2- Mr.Araka Page 1


WEB DESIGN, PROGRAMMING AND ADMINISTRATION

UNIT 1 : INTRODUCTION

All students should be familiar with the concepts of html and cascading stylesheets.

The following software is required to study PHP:

• A code editor. A code editor is a text editor that is specifically designed for writing code. It
provides features such as syntax highlighting, code completion, and debugging tools. Some
popular code editors include Visual Studio Code, Sublime Text, and Atom.
• A web development environment (WDE). A WDE is a software environment that allows you to
develop web applications locally on your computer. It includes a web server, database server,
and PHP interpreter. Some popular WDEs include WAMP,XAMPP, LAMP, and MAMP.
• A web browser. A web browser is used to view the results of your PHP code. Any modern web
browser, such as Google Chrome, Mozilla Firefox, or Microsoft Edge, will work.

Optional software that can be helpful for studying PHP includes:

• A version control system (VCS). A VCS is a system that allows you to track changes to your
code and collaborate with other developers. Some popular VCSs include Git and Mercurial.
• A debugger. A debugger is a tool that allows you to step through your code line by line and
inspect the values of variables. This can be helpful for finding and fixing bugs in your code.
Some popular debuggers include Xdebug and PHP Debugger.
• A documentation generator. A documentation generator is a tool that can generate
documentation for your PHP code. This can be helpful for documenting your code and making it
easier to understand and maintain. Some popular documentation generators include
phpDocumentor and Sphinx.
PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used,
free, and efficient alternative to competitors such as Microsoft's ASP.

What is PHP?

It allows web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications.

• PHP stands for PHP: Hypertext Preprocessor

• PHP is a server-side scripting language, like ASP .

BCS&BIT 2.2- Mr.Araka Page 2


A scripting language is a programming language that is interpreted..its translated into machine
code when the code is run. All scripting languages are programming languages but not all
programming languages are scripting languages.

• 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

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"

What is MySQL?

• MySQL is a database server

• MySQL is ideal for both small and large applications

• MySQL supports standard SQL

• MySQL compiles on a number of platforms. PHP is compatible with almost all servers used
today (Apache, IIS, etc.)

• MySQL is free to download and use

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a
Unix platform). PHP runs on different platforms (Windows, Linux, Unix, etc.)

BCS&BIT 2.2- Mr.Araka Page 3


Where is PHP used?

Three are the main areas where PHP scripts are used:

• Server-side scripting

This is the most used and main target for PHP. You need three things to make this work the way
you need it. The PHP parser (CGI or server module), a web server and a web browser.

You need to run the web server where You can access the PHP program output with a web
browser, viewing the PHP page through the server. All these can run on your home machine if
you are just experimenting with PHP programming.

• Command line scripting

You can make a PHP script to run it without any server or browser. You only need the PHP
parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on
Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text
processing tasks.

• Writing desktop applications

PHP may not the very best language to create a desktop application with a graphical user
interface, but if you know PHP very well, and would like to use some advanced PHP features in
your client-side applications you can also use PHP-GTK to write such programs. You also have
the ability to write cross-platform applications this way. In this article, we’ll have a detailed look
at the server-side scripting using PHP.

Why PHP?

Why PHP is so popular today:

• Compatible with almost all servers used nowadays

A web server is an information technology that processes requests via HTTP, the basic network
protocol used to distribute information on the World Wide Web. There exist many types of web
servers that servers use. Some of the most important and well-known are: Apache HTTP Server,
IIS (Internet Information Services), lighttpd, Sun Java System Web Server etc. As a matter of
fact, PHP is compatible with all these web servers and many more.

• PHP will run on most platforms

Unlike some technologies that require a specific operating system or are built specifically for
that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux, Unix etc)

BCS&BIT 2.2- Mr.Araka Page 4


• PHP supports such a wide range of databases

An important reason why PHP is so used today is also related to the various databases it supports
(is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo, MaxDB,
MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so on.

• PHP is free to download and open source

Anyone can start using PHP right now by downloading it from php.net. Millions of people are
using PHP to create dynamic content and database-related applications that make for outstanding
web systems. PHP is also open source, which means the original source code is made freely
available and may be redistributed and modified.

• Easy to learn & large community

PHP is a simple language to learn step by step. This makes it easier for people to get engaged in
exploring it. It also has such a huge community online that is constantly willing to help you
whenever you’re stuck (which actually happens quite a lot).

The following is a list of popular PHP frameworks

• Laravel
• Symfony
• Yii
• CodeIgniter
• Laminas Project (formerly Zend Framework)
• CakePHP
• Phalcon
• Slim Framework
• FuelPHP
• PHPPixie
• Fat-Free Framework

As of today, the following PHP versions are available:

• Supported versions:

BCS&BIT 2.2- Mr.Araka Page 5


o PHP 8.2 (latest)
o PHP 8.1 (security fixes only)
o PHP 8.0 (security fixes only)
• Unsupported versions:
o PHP 7.4
o PHP 7.3
o PHP 7.2

Advantages of PHP

The popularity of PHP is growing rapidly because of its many advantages:

• It’s fast. Because it is embedded in HTML code, the response time is short.
• It’s inexpensive — free, in fact. PHP is proof that free lunches do exist and that you can
get more than you paid for.
• It’s easy to use. PHP contains many special features and functions needed to create
dynamic Web pages. The PHP language is designed to be included easily in an HTML
file.
• It can run on many operating systems. It runs on a variety of operating systems —
Windows, Linux, Mac OS, and most varieties of Unix.
• It’s available on almost all Web hosts. If you are going to publish your Web site on a
Web host, you will find PHP installed on almost all Web hosts for free.
• Technical support is widely available. A large base of users provides free support
through e-mail discussion lists.
• It’s secure. The user does not see the PHP code.
• It’s designed to support databases. PHP includes functionality designed to interact
with specific databases. It relieves you of the need to know the technical details required
to communicate with a database.
• It’s customizable. The open source license allows programmers to modify the PHP
software, adding or modifying features as needed to fit their own specific environments

BCS&BIT 2.2- Mr.Araka Page 6


Understanding PHP Basics

Learning a new language is not easy. You need to understand not only the syntax of the
language, but also its grammatical rules, that is, when and why to use each element of the
language

PHP code is executed on the server, and the plain HTML result is sent to the browser.

Basic PHP Syntax

A PHP scripting block always starts with ..

For maximum compatibility, we recommend that you use the standard form

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code

There are four ways the PHP parser engine can differentiate PHP code in a webpage:

• Canonical PHP Tags This is the most popular and effective PHP tag style and looks like this:

<?php…..?>

• Short-open Tags

These are the shortest option, but they might need a bit of configuration, and you might either
choose the --enable-shorttags configuration option when building PHP, or set the short_open_tag
setting in your php.ini file.

<?. .. ... ?>

• ASP-like Tags

In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:

<%.........%>

• HTML script Tags

You can define a new script with an attribute language like so:

<script language=”php”>……..</script>

BCS&BIT 2.2- Mr.Araka Page 7


<?
print("Hello World");
echo "Hello World";
printf("Hello World");
?>

The result of the above statements would be the same: "Hello World". But why are there three
different ways to output?

• print returns a value. It always returns 1.


• echo can take a comma delimited list of arguments to output.
• printf is a direct analog of C’s printf().

echo and print are more or less the same. They are both used to output data to the screen. The
differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another. There are two basic statements to output text
with PHP: echo and print. In the example above we have used the echo statement to output the
text "Hello World"

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

Commenting PHP
Just like other languages, there are several ways to comment PHP code.
Let’s have a look at the most useful ones:

Use # to write single-line comments


Eg

BCS&BIT 2.2- Mr.Araka Page 8


<?
# this is a comment in PHP, a single line comment
?>

Use // to also write single-line comments


<?
// this is also a comment in PHP, a single line comment
?>

Use /* ...*/ to write multi-line comments


<?
/*
this is a multi line comment
Name: Web Code Geeks
Type: Website
Purpose: Web Development
*/
?>

BCS&BIT 2.2- Mr.Araka Page 9


UNIT 2: VARIABLES ,OPERATORS AND EXPRESSIONS

Variables in PHP

Variables are the building blocks of any programming language. A variable can be thought of as
a programming construct used to store both numeric and nonnumeric data. The contents of a
variable can be altered during program execution, and variables can be compared and
manipulated using operators.

A variable is used to store information. Variable names in PHP are case-sensitive. As a result the
variables $color, $Color and $COLOR are treated as three different variables.

Variables are used for storing values, like text strings, numbers or arrays. When a variable is
declared, it can be used over and over again in your script.

All variables in PHP start with a $ sign symbol.

The correct way of declaring a variable in PHP.

$var_name = value;

In PHP, variables do not need to be declared before assignment.

The main data types used to construct variables are:

1. Integers -
▪ They are whole numbers, without a decimal point, like 4195.
▪ They are the simplest type.
▪ They correspond to simple whole numbers, both positive and negative.
Integers can be assigned to variables, or they can be used in expressions,
like $int_var = 12345;$another_int = -12345 + 12345;
▪ Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base
16) format. Decimal format is the default, octal integers are specified with
a leading 0, and hexadecimals have a leading 0x.
2. Doubles –
▪ floating-point numbers like 46.2, 733.21 etc
▪ They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed.
3. Booleans -
▪ They have only two possible values either true or false.
▪ PHP provides a couple of constants especially for use as Booleans: TRUE
and FALSE,
4. Strings - set of characters, like KIUT
5. Arrays - named and indexed collections of other values

BCS&BIT 2.2- Mr.Araka Page 10


6. Objects - instances of predefined classes
7. NULL – For variable that have not be given a value or have been unset
▪ NULL is a special type that only has one value: NULL.
▪ To give a variable the NULL value, simply assign it like this $my_var =
NULL;
▪ The special constant NULL is capitalized by convention, but actually it is
case insensitive; you could just as well have typed $my_var = null;
8. Resource – external resources like DB connections or file pointers

Testing for a Specific Data Type


PHP provides a special function corresponding to each data type.
These functions accept a variable or value and return a Boolean

There are numerous functions available for determining the data type of variables

• getType( )
• is_array( )- Returns true if the argument is an array
• is_double( )- Returns true if the argument is a double
• is_float( ), is_real( )
• is_long( ),
• is_int( )-Returns true if the argument is an integer
• is_string( )- Returns true if the argument is a string
• is_object( )- Returns true if the argument is an object
• is_resource( )- Returns true if the argument is a resource
• is_null( )- Returns true if the argument is null
• is_scalar( ) – check for integer, Boolean, string, or float
• is_numeric( ) – check for number or numeric string
• is_callable( ) – checks for valid function name
• is_bool() -Returns true if the argument is boolean

Each of these takes a variable as an argument and returns true or false

There is also a settype( $var, ‘type’ ) function that can be used to set a specific type

BCS&BIT 2.2- Mr.Araka Page 11


• Type can also be manipulated through the use of casting

// Casting

$totalamount = (float)$totalqty;

The following snippet shows all of these data types declared as variables:

<?

$intNum = 472;

$doubleNum = 29.3;

$boolean = true;

$string = ’bcs’;

$array = array("Pineapple", "Grapefruit", "Banana");

// creating a class before declaring an object variable

class person {

function agePrint() {

$age = 5;

echo "This person is $age years old!";

// creating a new object of type person

$object = new person;

?>

Naming Rules for Variables

• A variable name must start with a letter or an underscore "_"

• A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and
_)

BCS&BIT 2.2- Mr.Araka Page 12


• A variable name should not contain spaces. If a variable name is more than one word, it should
be separated with an underscore ($my_string), or with capitalization ($myString)

Variable Scope

• At this point we know that all variables have an identifier, a data type, and a value.
• All variables also have a scope.
o The scope of a variable refers to the places in a script where a variables can be
used.

In PHP, variables can be declared anywhere in the script. The scope of a variable
is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:

<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$x = 5; // local scope

BCS&BIT 2.2- Mr.Araka Page 13


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>";
?>
</body>
</html>

PHP The global Keyword


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):
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
</body>
</html>

PHP The static Keyword


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:
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();

BCS&BIT 2.2- Mr.Araka Page 14


echo "<br>";
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.

Example code on variables

PHP can be used for creating dynamic websites. In a dynamic website, user can
interact with website by providing text or by selecting options. Form is one of the
quickest and easiest ways to add interactivity to our website. Through forms we
can read user data into PHP variables.

Sample form

Home.html

< html>

< head>

< body>

< form action=" message . PHP" method =" post"> Enter your message:

< input type=" text" name=" MSG"=" 30">

< input type=" submit" value=" send ">

</ form>

</ body>

</ html>

Message. php

<? PHP

BCS&BIT 2.2- Mr.Araka Page 15


// retrieve form data in a variable

$input=$- post[" MSG"];

// print it

echo " you said <i> $input </i>”

?>

Output

You said: Hello

Explanation

Here we have used HTML coding for displaying the input box. The <form> tag of
html isused with input option. The form tag also contains two main attributes
action and method.

The action attribute specifies the name of the script. Here the name is
message.php. The script will process the message entered into the form. The
method attribute of the < form> tag specifies the manner in which form data will
be submitted. Here it is POST method.

We have to run the home.html file in a browser. This is a client side script. On
running this file a form is displayed in the webpage with a line.When we click the
submit button the server side script in the action attribute will be called for
execution. That script will display another webpage that prints the string we have
entered.The $_POST variable would have stored the string we have entered. It
will be stored in $_POST[‘msg’]. Then it will be assigned to php variable
$input.We can display it using echo statement

Constants

Constants are like variables except that once they are defined they cannot be
changed or undefined.

A constant is an identifier (name) for a simple value. The value cannot be


changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name). Note: Unlike variables, constants are automatically global across
the entire script.

BCS&BIT 2.2- Mr.Araka Page 16


Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

name: Specifies the name of the constant

value: Specifies the value of the constant

case-insensitive: Specifies whether the constant name should be case-

insensitive. Default is false

The example below creates a constant with a case-sensitive name:

<!DOCTYPE html>

<html>

<body>

<?php

// case-sensitive constant name

define("GREETING", "Welcome to Tanzania!");

echo “GREETING”;

?>

</body>

</html>

The example below creates a constant with a case-insensitive name:

<!DOCTYPE html>

<html>

BCS&BIT 2.2- Mr.Araka Page 17


<body>

<?php

// case-insensitive constant name

define("GREETING", "Welcome to Tanzania", true);

echo greeting;

?>

</body>

</html>

NOTE

Constants are automatically global and can be used across the entire script.

Operators

PHP Operator is a symbol i.e used to perform operations on operands.

In simple words, operators are used to perform operations on variables or values.

PHP Operators can be categorized in following forms:

a. Arithmetic Operators

b. Assignment Operators

c. Bitwise Operators

d. Comparison Operators

e. Incrementing/Decrementing Operators

f. Logical Operators

g. String Operators

h. Array Operator

BCS&BIT 2.2- Mr.Araka Page 18


Arithmetic operators:

The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.

Assignment Operators

The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".

BCS&BIT 2.2- Mr.Araka Page 19


Bitwise operators

The bitwise operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.

Comparison Operators

Comparison operators allow comparing two values, such as number or string.


Below the list of comparison operators are given

BCS&BIT 2.2- Mr.Araka Page 20


Incrementing/Decrementing Operators

The increment and decrement operators are used to increase and decrease the
value of a variable.

BCS&BIT 2.2- Mr.Araka Page 21


Logical Operators

The logical operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.

String Operators

The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:

BCS&BIT 2.2- Mr.Araka Page 22


Operator precedence

You can add multiple operators to an expression to make it as long as it needs to


be, but you need to be careful as some operators have higher precedence than
others, and thus, the order of execution might not be the one you expect. The
following table shows the order of precedence of the operators

For example the expression 3+2*3 will first evaluate the product 2*3 and then the
sum, so the result is 9 rather than 15. If you want to perform operations in a
specific order, different from the natural order of precedence, you can force it by
enclosing the operation within parentheses. Hence, (3+2)*3 will first perform the
sum and then the product, giving the result 15 this time

BCS&BIT 2.2- Mr.Araka Page 23


UNIT 3: PHP CONTROL STRUCTURES

Control structures

▪ Control structure allows you to control the flow of code execution in your
application.
▪ Generally, a program is executed sequentially, line by line, and a control
structure allows you to alter that flow, usually depending on certain
conditions

PHP 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.
▪ Conditional statements are statements that can only be executed when a certain particular
condition is fulfilled.

a) The If statement
The if statement executes a piece of code if a condition is true. The syntax is

if (condition)
{
// code to be executed in case the condition is true
}

A practical example would be:

<?php
$age = 18;
if ($age < 20)
{
echo "You are a teenager";
}
?>

BCS&BIT 2.2- Mr.Araka Page 24


Example 2
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>

Note The code is executed only if the specified condition is true.

b) if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.

Syntax

if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Example

<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>

BCS&BIT 2.2- Mr.Araka Page 25


</body>
</html>

c) if...elseif....else Statement
If you've got more than two choices to choose from, you can use the elseif statement.

Syntax
if (expression1)
{
// code is executed if the expression1 evaluates to TRUE
}
elseif (expression2)
{
// code is executed if the expression2 evaluates to TRUE
}
elseif (expression3)
{
// code is executed if the expression3 evaluates to TRUE
}
else
{
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a
default choice
}

Example

<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>

BCS&BIT 2.2- Mr.Araka Page 26


d) Switch Statement
The switch statement is somewhat similar to the elseif statement which we've just discussed
in the previous section.
Use the switch statement to select one of many blocks of code to be executed.
The switch statement works with two other keywords: case and break. The case keyword is
used to test a label against a value from the round brackets. If the label equals to the value,
the statement following the case is executed. The break keyword is used to jump out of the
switch statement. There is an optional default statement. If none of the labels equals the
value, the default statement is 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;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically. The default
statement is used if no match is found.

Example 1
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":

BCS&BIT 2.2- Mr.Araka Page 27


echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>

Example 2

<?php
$domain = 'sk';
switch ($domain) {
case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}

Looping Statements

Computers often have to do the same task repetitively until some condition is
satisfied. loops are used to execute the same code block for a specified number of times.

a)The for loop

The for loop is used when the programmer knows in advance how many times the block
of code should be executed. This is the most common type of loop encountered in almost
every programming language.

Syntax

for (initialization; condition; increment/decrement)


{
// executable code
}

BCS&BIT 2.2- Mr.Araka Page 28


Parameters:

• initiliation: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).

Example
An example where we use the for loop would be:

<html>
<body>
<?php
for ($i=0; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>

The result of this code snippet would be:


This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

b)The while Loop

The while loop executes a block of code while a condition is true.


Its also called an entry controlled loop

Syntax

while (condition)
{
code to be executed;
}

BCS&BIT 2.2- Mr.Araka Page 29


example
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

c)The do...while Statement

The do...while statement will always execute the block of code once, it will then check
the condition,and repeat the loop while the condition is true.
Its also called an exit controlled loop

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

example
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>

BCS&BIT 2.2- Mr.Araka Page 30


</body>
</html>

d) foreach Loop
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):

example

<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) ``
{
echo "$value <br>";
}
?>
</body>
</html>

Arrays

Array is complex variable that enables us to store multiple values in a single variable. We use
this to store related information. An array is a special variable, which can hold more than one
value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

BCS&BIT 2.2- Mr.Araka Page 31


And what if you had not 3 cars, but 300?

The solution is to create an array! An array can hold many values under a single name, and you
can access the values by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an 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

PHP Indexed 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");

or
the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"

Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

<!DOCTYPE html>
<html>
<body>
<?php

BCS&BIT 2.2- Mr.Araka Page 32


$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
</body>
</html>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a
for loop, like this:

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
Also known as hash arrays

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";

We access element by using the key instead of position number

BCS&BIT 2.2- Mr.Araka Page 33


The named keys can then be used in a script:

<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a
foreach loop, like this:

<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.

The dimension of an array indicates the number of indices you need to select an
element.

•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

BCS&BIT 2.2- Mr.Araka Page 34


Two-dimensional Arrays
A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).
First, take a look at the following table:

We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 35


We can also put a For loop inside another For loop to get the elements of the
$cars array (we still have to point to the two indices):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>

Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,descending or
ascending.

Sort Functions For Arrays


The following are the PHP array sort functions:

▪ sort() - sort arrays in ascending order


▪ rsort() - sort arrays in descending order
▪ asort() - sort associative arrays in ascending order, according to the value
▪ ksort() - sort associative arrays in ascending order, according to the key
▪ arsort() - sort associative arrays in descending order, according to the value
▪ krsort() - sort associative arrays in descending order, according to the key

BCS&BIT 2.2- Mr.Araka Page 36


Sort Array in Ascending Order - sort()
The following example sorts the elements of the $cars array in ascending
alphabetical order
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

The following example sorts the elements of the $numbers array in ascending
numerical order:

<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 37


Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending
alphabetical order:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

The following example sorts the elements of the $numbers array in descending
numerical order:

<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 38


UNIT 4 :PHP FUNCTIONS
A function is a set of program statements that perform a specific task. Functions can be
called or executed from anywhere in the program. All the programming languages have
built-in
functions and also allow us to create user defined function

Importance of using functions

1. Reducing repetition:

User defined function enables developer to extract commonly used pieces of code as separate
package. These functions help developers avoid redundant work and focus more on the logic
rather than routine things.

2. Easy maintenance:-

Because functions are defined once and used many times, they are used to maintain the code.
During code maintenance if we want to change from values in calculation, we need to change
only in the function. We need not Traverse the whole program for making change in one value.

3. Improves abstraction:

Function forces programmer to think in abstract terms. We need not worry about implementation
of the function. It is enough that we know the function name, number of arguments and return
type of the function.

Functions can be divided into two parts


• User defined functions- functions defined by the user

• Built-in functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform
a specific task

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

BCS&BIT 2.2- Mr.Araka Page 39


Create a User Defined Function in PHP

There are two parts which should be clear to you

• Creating a Function

• Calling a Function

The basic syntax to create a function is

<?php

function functionName($argument1, $argument2...) {

// code to be executed

functionName($argument1, $argument2...); // function call

?>

Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and }, the arguments within the function are optional.

invoking function

<?php

….

….

displayShakesphearQuote();

?>

PHP functions are defined with the function keyword following by name of the function.

➢ The name of function should follow the rule for naming variables.

➢ After function name list of arguments enclosed in parenthesis() should be present.

➢ It is optional and can be omitted if no argument is present.

BCS&BIT 2.2- Mr.Araka Page 40


➢ After the first line of the function the body of the function should be present in between the
curly brackets {}.

➢ The function code can contain any valid PHP statements, which includes loops conditional
statements and call to other function.

➢ Invoking a function is done by calling a function with its name.

➢ If the function had arguments we have to specify the arguments during invoking

Example

<?php

//define a function

function displayQuote()

echo’some are born great, some achieve greatness and some have greatness through upon them’;.

displayQuote();

?>

Defining a Functions with Parameters and without Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters as you like.

Example of PHP script for function with argument.

<?php

//define a function

function triangle_area ($base,$height)

$area=$base*$height*0.5

return $area;

BCS&BIT 2.2- Mr.Araka Page 41


//invoke a function

$ta=triangle_area(10,50);

echo’the area of a triangle is $ta’;

?>

Another example function with arguments:

<?php

function greetPerson($name)

// function definition with arguments

echo "Hi there, ".$name;

// what this function does

greetPerson("Fabio"); // function call

greetPerson("Michael");

?>

More than one argument can be used in a function

example

<?php

function personProfile($name, $city, $job)

// function definition with arguments

echo "This person is ".$name." from ".$city.".";

echo "";

BCS&BIT 2.2- Mr.Araka Page 42


echo "His/Her job is ".$job.".";

personProfile("Fabio", "Tirana", "Web Dev");

echo "";

personProfile("Michael", "Athens", "Graphic Designer");

echo "";

personProfile("Xena", "London", "Tailor");

?>

Returning value from the function

A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.

To let a function return a value, use the return statement:

You can return more than one value from a function using return array(1,2,3,4).

Example:

<html>

<head>

<title>Writing PHP Function which returns value</title>

</head>

<body>

<?php

function addFunction($num1, $num2) {

$sum = $num1 + $num2;

return $sum;

$return_value = addFunction(10, 20);

BCS&BIT 2.2- Mr.Araka Page 43


echo "Returned value from the function : $return_value";

?>

</body>

</html>

This will display following result −

Returned value from the function : 30

Types of errors in PHP

Basically, an error is a mistake in a program that may be caused by writing incorrect syntax or
incorrect code. An error message is displayed on your browser containing the filename along
with location, a message describing the error, and the line number in which error has occurred.

There are usually different types of error. In PHP, mainly four types of errors are considered:

1. Syntax Error or Parse Error

2. Fatal Error

3. Warning Error

4. Notice Error

Syntax Error or Parse Error

A syntax error is a mistake in the syntax of source code, which can be done by programmers due
to their lack of concern or knowledge. It is also known as Parse error. Compiler is used to catch
the syntax error at compile time.

Fatal Error

A fatal error is another type of error, which is occurs due to the use of undefined function. The
PHP interpreter understands the PHP code but also recognizes the undefined function. This
means that when a function is called without providing its definition, the PHP interpreter
generates a fatal error.

Warning Error

BCS&BIT 2.2- Mr.Araka Page 44


A warning is generated when the programmer tries to include a missing file. The PHP function
calls that missing file which does not exist. The warning error does not stop/prevent the
execution of the program. The main reason behind generating a warning error is to pass an
incorrect number of parameters to a function or to include a missing file

Notice Error

Notice error is same as warning error. When a program contains something wrong, the notice
error occurs. But it allows/continue the execution of the program with a notice error. Notice error
does not prevent the execution of the code. For example - access to undefined variable.

Include and require:- functions

Advantage of the function are realised when the function or statement calling the function
remains in the same script (same PHP file). we can also use function that can be defined in other
PHP files by importing the function definition.

For importing, PHP provides two useful functions. They are

(i) include()

(ii) require()

Eg:

Using include()

<?php

//import file

include (“c:/php files /files.php”)

//we can call functions from files.php here.

?>

Include function generates warning message if the value in the file or function cannot

be found but the execution of script continues. The include() function takes all the content in a
specified file and includes it in the current file.

BCS&BIT 2.2- Mr.Araka Page 45


Example 2

Assume we have a standard menu file, called "menu.php", that should be used on all pages:

<a href="/default.php">Home</a>

<a href="/tutorials.php">Tutorials</a>

<a href="/references.php">References</a>

<a href="/examples.php">Examples</a>

<a href="/about.php">About Us</a>

<a href="/contact.php">Contact Us</a>Some text.

</html

All pages in the Web site should include this menu file. Here is how it can be done:

<html>

<body>

<div class="leftmenu">

<?php include("menu.php"); ?>

</div>

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

<p>Some text.</p>

</body>

</html>

Using include_once

Each time you issue the include directive, it includes the requested file again, even if you’ve already
inserted it. For instance, suppose that library.php contains a lot of useful functions, so you include it in
your file. Now suppose you also include another library that includes library.php. Through nesting,
you’ve inadvertently included library.php twice. This will produce error messages, because you’re trying
to define the same constant or function multiple times. To avoid this problem, use include_once instead.

. Including a PHP file only once

BCS&BIT 2.2- Mr.Araka Page 46


<?php

include_once "library.php";

// Your code goes here

?>

Require function:-

Ex:-

<?php

//import files

require(“c:/php files /First.php”)

//we can call function from the first.php here

?>

The require function forces file to be included in the script. If the file or function cannot be

found. It generates fatal error. This error stops script execution.

Requiring a PHP file only once

<?php

require_once "library.php";

// Your code goes here

?>

Defining global and local variable:-


The variables defined inside functions are local variables. They cannot be used from outside the
function. If we want to use a variable throughout the script in all functions we have to declare
that variable with Global key word.

Global variable can be used in PHP script for counting the number of visitors in a website. This
is done by the following statement.

Global $count

BCS&BIT 2.2- Mr.Araka Page 47


Super Global variables:-
There are some variables provided by the PHP interpreter that we can use in our PHP script.
These variables can be accessed from anywhere in our program. There are variables which are
used commonly for creation of websites with many web pages. All these Global

variables starts with $_

They are

1.$_SERVER is a super global variable which holds information about headers, paths and script
locations.

Eg.

<?php

Echo $_SERVER[‘PHP_SELF’];

Echo $_SERVER[‘SERVER_NAME’];

Echo “<br>”;

Echo $_SERVER[‘HTTP_HOST’];

Echo “<br>”;

Echo Echo “<br>”;

$_SERVER[‘HTTP_REFERER’];

Echo “<br>”;

Echo $_SERVER[‘HTTP_USER_AGENT’];

?>

2. $_POST

Used to collect data after submitting HTML form with method =" post"

html>
<body>

<form method="post" action="”>

BCS&BIT 2.2- Mr.Araka Page 48


<?php echo $_SERVER['PHP_SELF'];

?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

3. $_GET

Collect form data after submitting HTML form with method = "GET"

<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

4.$_REQUEST

Used to collect data after submitting an HTML form.

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

BCS&BIT 2.2- Mr.Araka Page 49


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

5.$_GLOBALS

It contains all the super Global variables in installed PHP version.

<?php
function test() {
$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";


echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";


test();
?>

6.$_FILES –

It contains names, sizes, and mime types of files uploaded in the current HTTP request.

<?php
echo "Filename: " . $_FILES['file']['name']."<br>";
echo "Type : " . $_FILES['file']['type'] ."<br>";
echo "Size : " . $_FILES['file']['size'] ."<br>";
echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
echo "Error : " . $_FILES['file']['error'] . "<br>";
?>

BCS&BIT 2.2- Mr.Araka Page 50


7.$_SESSION- A session is a way to store information (in variables) to be used across multiple
pages.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

8.$_COOKIE-

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

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

BCS&BIT 2.2- Mr.Araka Page 51


</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 52


WORKING WITH DATABASES

A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those type of systems.

Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different
tables and relations are established using primary keys or other keys known as Foreign Keys.

A Relational DataBase Management System (RDBMS) is a software that −

➢ Enables you to implement a database with tables, columns and indexes.


➢ Guarantees the Referential Integrity between rows of various tables.
➢ Updates the indexes automatically.
➢ Interprets an SQL query and combines information from various tables.

RDBMS Terminology

a) Database- acollection of tables with related data


b) Table − A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
c) Column − One column (data element) contains data of one and the same kind, for
example the column postcode.
d) A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
e) Redundancy − Storing data twice, redundantly to make the system faster.
f) Primary Key − A primary key is unique. A key value can not occur twice in one table.
With a key, you can only find one row.
g) Foreign Key − A foreign key is the linking pin between two tables.
h) Compound Key - also called a composite key is a key that is consists of multiple
columns because one column is not sufficiently unique.
i) Index − An index in a database resembles an index at the back of a book.
j) Referential Integrity- make sure that a foreign key value points to an existing row.

BCS&BIT 2.2- Mr.Araka Page 53


DBMS languages

Database languages are used to read, update and store data in a database. There are
several such languages that can be used for this purpose; one of them is SQL
(Structured Query Language).

a) DDL – Data Definition Language:


(CREATE,DROP,ALTER,TRUNCATE,COMMENT,RENAME)
b) DML – Data Manipulation Language: (INSERT, UPDATE,DELETE)
c) DCL – Data Control Language: (GRANT,REVOKE)
d) TCL-Transaction Control Language: (COMMIT,ROLLBACK)

a). DDL(Data Definition Language) : DDL or Data Definition Language actually


consists of the SQL commands that can be used to define the database schema. It simply
deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database.
i) CREATE – it is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).

There are two CREATE statements available in SQL:

• CREATE DATABASE
• CREATE TABLE

BCS&BIT 2.2- Mr.Araka Page 54


CREATE DATABASE
A Database is defined as a structured set of data. So, in SQL the very first step to store
the data in a well structured manner is to create a database. The CREATE DATABASE
statement is used to create a new database in SQL.
Syntax: CREATE DATABASE database_name;

Example: SQL> CREATE DATABASE Employee;


In order to get the list of all the databases, you can use
SHOW DATABASES statement.

Example – SQL> SHOW DATABASES

CREATE TABLE:

The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of
rows and columns. So while creating tables we have to provide all the information to SQL about the
names of the columns, type of data to be stored in columns, size of the data etc.

Let us now dive into details on how to use CREATE TABLE statement to create tables in SQL.

Syntax:

CREATE TABLE table_name ( column1 data_type(size), column2 data_type(size), column3


data_type(size), .... );

Example Query:

This query will create a table named Students with three columns, ROLL_NO, NAME and SUBJECT.

CREATE TABLE Students ( ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(20), );

ii) DROP:

DROP is used to delete a whole database or just a table.

The DROP statement destroys the objects like an existing database, table, index, or view.

A DROP statement in SQL removes a component from a relational database management system
(RDBMS).

Syntax: DROP object object_name; Examples: DROP TABLE table_name;

table_name: Name of the table to be deleted.

DROP DATABASE database_name; database_name: Name of the database to be deleted.

BCS&BIT 2.2- Mr.Araka Page 55


iii) TRUNCATE

It is used to remove all records from a table, including all spaces

The TRUNCATE TABLE mytable statement is logically (though not physically) equivalent to the
DELETE FROM mytable statement (without a WHERE clause).

Syntax: TRUNCATE TABLE table_name;

DROP vs TRUNCATE

Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.

Truncate preserves the structure of the table for future use, unlike drop table where the table is deleted
with its full structure.

Table or Database deletion using DROP statement cannot be rolled back, so it must be used wisely.

To delete the whole database

DROP DATABASE student_data; After running the above query whole database will be deleted.

To truncate Student_details table from student_data database. TRUNCATE TABLE Student_details;

iv) ALTER (ADD, DROP, MODIFY) ALTER TABLE

is used to add, delete/drop or modify columns in the existing table.

It is also used to add and drop various constraints on the existing table.

ALTER TABLE – ADD:

ADD is used to add columns into the existing table. Sometimes we may require to add additional
information, in that case we do not require to create the whole database again, ADD comes to our rescue.

Syntax:

ALTER TABLE table_name ADD (Columnname_1 datatype, Columnname_2 datatype,


… Columnname_n datatype);

ALTER TABLE – DROP COLUMN

is used to drop column in a table. Deleting the unwanted columns from the table.

Syntax:

ALTER TABLE table_name DROP COLUMN column_name;

BCS&BIT 2.2- Mr.Araka Page 56


ALTER TABLE-MODIFY

It is used to modify the existing columns in a table. Multiple columns can also be modified at once.
ALTER TABLE table_name MODIFY column_name column_type;

QUERY:

To ADD 2 columns AGE and COURSE to table Student.

ALTER TABLE Student ADD (AGE number(3),COURSE varchar(40));

MODIFY column COURSE in table Student

ALTER TABLE Student MODIFY COURSE varchar(20);

v) Comments

As is any programming languages comments matter a lot in SQL also. In this set we will learn about
writing comments in any SQL snippet.

Comments can be written in the following three formats:

• Single line comments.


• Multi line comments
• In line comments

b). DML(Data Manipulation Language) :

The SQL commands that deals with the manipulation of data present in the database belong to DML or
Data Manipulation Language and this includes most of the SQL statements.

i) SELECT Statement

select statement is used to fetch data from relational database. A relational database is organized
collection of data. As we know that data is stored inside tables in a database.

SQL select statement or SQL select query is used to fetch data fro m one or more than one tables.

SELECT One column: Here column_name is the name of the column for which we need to fetch data
and table_name is the name of the table in the database.

SELECT column_name FROM table_name;

More than one columns:

SELECT column_name_1, column_name_2, ... FROM table_name;

To fetch the entire table or all the fields in the table:

BCS&BIT 2.2- Mr.Araka Page 57


SELECT * FROM table_name;

Example:

SELECT EMP_NAME FROM EMPLOYEES;

To fetch the entire EMPLOYEES table:

SELECT * FROM EMPLOYEES;

Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:

SELECT ROLL_NO, NAME, AGE FROM Student;

ii). INSERT INTO Statement

The INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using
INSERT INTO statement for inserting rows:

a)Only values: First method is to specify only the value of data to be inserted without the column names.

INSERT INTO table_name VALUES (value1, value2, value3,…);

b)Column names and values both: In the second method we will specify both the columns which we
want to fill and their corresponding values as shown below:

INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..); \

Example: Method 1 (Inserting only values) :

INSERT INTO Student VALUES (‘5′,’HARSH’,’WEST BENGAL’,’XXXXXXXXXX’,’19’);

Method 2 (Inserting values in only specified columns):

INSERT INTO Student (ROLL_NO, NAME, Age) VALUES (‘5′,’PRATIK’,’19’);

iii).UPDATE Statement

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update
single columns as well as multiple columns using UPDATE statement as per our requirement. Basic
Syntax:

UPDATE TableName SET column_name1 = value, column_name2 = value.... WHERE condition;

EX1: SQL> UPDATE EMPLOYEES SET EMP_SALARY = 10000 WHERE EMP_AGE > 25;

BCS&BIT 2.2- Mr.Araka Page 58


EX2; SQL> UPDATE EMPLOYEES SET EMP_SALARY = 120000 WHERE EMP_NAME = 'Apoorv';

iv). DELETE Statement

The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single
record or multiple records depending on the condition we specify in the WHERE clause.

Basic Syntax:

DELETE FROM table_name WHERE some_condition;

Deleting single record:

Delete the rows where NAME = ‘Ram’. This will delete only the first row. DELETE FROM Student
WHERE NAME = 'Ram';

Deleting multiple records: Delete the rows from the table Student where Age is 20. This will delete 2
rows(third row and fifth row).

DELETE FROM Student WHERE Age = 20; Delete all of the records:

There are two queries to do this as shown below,

query1: "DELETE FROM Student";

query2: "DELETE * FROM Student";

c). DCL(Data Control Language) :

DCL includes commands such as GRANT and REVOKE which mainly deals with the rights, permissions
and other controls of the database system.

Examples of DCL commands:

i). GRANT-gives user’s access privileges to database.

ii). REVOKE-withdraw user’s access privileges given by using the GRANT command.

d). TCL (transaction Control Language) :

TCL commands deals with the transaction within the database. Examples of TCL commands:

i). COMMIT– commits a Transaction.

ii). ROLLBACK– rollbacks a transaction in case of any error occurs.

BCS&BIT 2.2- Mr.Araka Page 59


ii). SAVEPOINT–sets a savepoint within a transaction.

iv). SET TRANSACTION–specify characteristics for the transaction.

JOINS IN RDBMS
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

Join in DBMS is a binary operation which allows you to combine join product and selection in one single
statement.

The goal of creating a join condition is that it helps you to combine the data from two or more DBMS
tables. The tables in DBMS are associated using the primary key and foreign keys.

Types of SQL JOIN

1. INNER JOIN

2. LEFT JOIN

3. RIGHT JOIN

4. FULL JOIN

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is
satisfied. It returns the combination of all rows from both the tables where the condition satisfie

BCS&BIT 2.2- Mr.Araka Page 60


Syntax

SELECT table1.column1, table1.column2 FROM table1 INNER JOIN table2 ON


table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE INNER JOIN PROJECT ON


PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Example

EMPLOYEE Table

BCS&BIT 2.2- Mr.Araka Page 61


2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the right table. If
there is no matching join value, it will return NULL.

Syntax

SELECT table1.column1, table1.column2 FROM table1 LEFT JOIN table2 ON table1.matching_column


= table2.matching_column;

Query

BCS&BIT 2.2- Mr.Araka Page 62


SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE LEFT JOIN PROJECT ON
PROJECT.EMP_ID = EMPLOYEE.EMP_ID; (NOTE REFER THE TABLE ABOVE)

4.RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched
values from the left table. If there is no matching in both tables, it will return NULL.

BCS&BIT 2.2- Mr.Araka Page 63


Syntax

SELECT table1.column1, table1.column2 FROM table1 RIGHT JOIN table2 ON table1.matching_column


= table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE RIGHT JOIN PROJECT ON


PROJECT.EMP_ID = EMPLOYEE.EMP_ID; (NOTE REFER THE TABLE ABOVE)

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have all the
records from both tables. It puts NULL on the place of matches not found.

BCS&BIT 2.2- Mr.Araka Page 64


Syntax

SELECT table1.column1, table1.column2 FROM table1 FULL JOIN table2 ON table1.matching_column


= table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE FULL JOIN PROJECT ON


PROJECT.EMP_ID = EMPLOYEE.EMP_ID; (NOTE REFER THE TABLE ABOVE)

Output

BCS&BIT 2.2- Mr.Araka Page 65


MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is becoming
so popular because of many good reasons −

• MySQL is released under an open-source license. So you have nothing to pay to use it.
• MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL works on many operating systems and with many languages
• including PHP, PERL, C, C++, JAVA, etc.
• MySQL works very quickly and works well even with large data sets.
• MySQL is very friendly to PHP, the most appreciated language for web development.
• MySQL supports large databases, up to 50 million rows or more in a
• table. The default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).
• MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific
environments.

MySQL uses many different data types broken into three categories −

• Numeric
• Date and Time
• String Types.

Numeric Data Types

MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you.

The following list shows the common numeric data types and their descriptions −

INT

A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a
width of up to 11 digits.

TINYINT

A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If
unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.

BCS&BIT 2.2- Mr.Araka Page 66


SMALLINT

A small integer that can be signed or unsigned. If signed, the allowable

range is from - 32768 to 32767. If unsigned, the allowable range is from 0 to

65535. You can specify a width of up to 5 digits.

MEDIUMINT

A medium-sized integer that can be signed or unsigned. If signed, the

allowable range is from -8388608 to 8388607. If unsigned, the allowable

range is from 0 to 16777215. You can specify a width of up to 9 digits.

BIGINT

A large integer that can be signed or unsigned. If signed, the allowable range

is from -

9223372036854775808 to 9223372036854775807. If unsigned, the allowable

range is from 0 to 18446744073709551615. You can specify a width of up to

20 digits.

FLOAT(M,D)

A floating-point number that cannot be unsigned. You can define the

display length (M) and the number of decimals (D). This is not required and

will default to 10,2, where 2 is the number of decimals and 10 is the total

number of digits (including decimals). Decimal precision can go to 24 places

for a FLOAT.

DOUBLE(M,D)

A double precision floating-point number that cannot be unsigned. You can define the display length (M)
and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of
decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.

BCS&BIT 2.2- Mr.Araka Page 67


DECIMAL(M,D)

An unpacked floating-point number that cannot be unsigned. In the unpacked decimals, each decimal
corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required.
NUMERIC is a synonym for DECIMAL.

Date and Time Types

The MySQL date and time data types are as follows −

DATE

A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th,
1973 would be stored as 1973-12-30.

DATE TIME

A date and time combination in YYYY-MM-DD HH:MM:SS format,between 1000-01-01 00:00:00 and
9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as
1973-12-30 15:30:00.

TIME STAMP

A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like the previous
DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December
30th, 1973 would be stored as 19731230153000 (YYYYMMDDHHMMSS).

TIME

Stores the time in a HH:MM:SS format.

YEAR(M)

Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR
can be between 1970 to 2069 (70 to 69).

If the length is specified as 4, then YEAR can be 1901 to 2155. The default length is 4.

String Types

Although the numeric and date types are f un, most data you'll store will be in a string format. This list
describes the common string datatypes in MySQL.

CHAR(M)

A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with
spaces to the specified length when stored. Defining a length is not required, but the default is 1.

VARCHAR(M)

BCS&BIT 2.2- Mr.Araka Page 68


A variable-length string between 1 and 255 characters in length. For

example, VARCHAR(25). You must define a length when creating a VARCHAR field.

BLOB or TEXT

A field with a maximum length of 65535 characters. BLOBs are"Binary Large Objects" and are used to
store large amounts of binary data,

such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The
difference between the two is that the sorts and comparisons on the stored data are case sensitive on
BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.

TINYBLOB or TINYTEXT

A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with
TINYBLOB or TINYTEXT.

MEDIUMBLOB or MEDIUMTEXT

A BLOB or TEXT column with a maximum length of 16777215 characters. You do not specify a length
with MEDIUMBLOB orMEDIUMTEXT.

LONGBLOB or LONGTEXT

A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a
length with LONGBLOB or LONGTEXT.

ENUM

An enumeration, which is a fancy term for list. When defining an ENUM, you are

creating a list of items from which the value must be selected (or it can be

NULL). For example, if you wanted your field to contain "A" or "B" or "C",

you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever
populate that field.

BCS&BIT 2.2- Mr.Araka Page 69


PHP MySQLi Functions

The MySQLi functions allows you to access MySQL database servers.

mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation

mysqli_autocommit() Turns on or off auto-committing database modifications

mysqli_change_user() Changes the user of the specified database connection

mysqli_character_set_name() Returns the default character set for the database connection

mysqli_close() Closes a previously opened database connection

mysqli_commit() Commits the current transaction

mysqli_connect_errno() Returns the error code from the last connection error

mysqli_connect_error() Returns the error description from the last connection error

mysqli_connect() Opens a new connection to the MySQL server

mysqli_data_seek() Adjusts the result pointer to an arbitrary row in the result-set

mysqli_debug() Performs debugging operations

mysqli_dump_debug_info() Dumps debugging info into the log

mysqli_errno() Returns the last error code for the most recent function call

mysqli_error_list() Returns a list of errors for the most recent function call

mysqli_error() Returns the last error description for the most recent function call

mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both

mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object

mysqli_fetch_field() Returns the next field in the result set, as an object

mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set

mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result set

mysqli_fetch_object() Returns the current row of a result set, as an object

BCS&BIT 2.2- Mr.Araka Page 70


mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated array

mysqli_field_count() Returns the number of columns for the most recent query

mysqli_field_seek() Sets the field cursor to the given field offset

mysqli_field_tell() Returns the position of the field cursor

mysqli_free_result() Frees the memory associated with a result

mysqli_get_charset() Returns a character set object

mysqli_get_client_info() Returns the MySQL client library version

mysqli_get_client_stats() Returns statistics about client per-process

mysqli_get_client_version() Returns the MySQL client library version as an integer

mysqli_get_connection_stats() Returns statistics about the client connection

mysqli_get_host_info() Returns the MySQL server hostname and the connection type

mysqli_get_proto_info() Returns the MySQL protocol version

mysqli_get_server_info() Returns the MySQL server version

MYSQL DATABASE CONNECTIVITY

Connect to a Database

Before you can access 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

Servername Optional. Specifies the server to connect to. Default value is "localhost:3306"

Username Optional. Specifies the username to log in with. Default value is the name of the user
that owns the server process

password Optional. Specifies the password to log in with. Default is ""

BCS&BIT 2.2- Mr.Araka Page 71


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","root","");

if (!$con)

die(“*** Connection FAILED***”);

} else {echo “*** Connection Succeeded ***";}

// some code

?>

Example 2

<?php

$username = "your_name";

$password = "your_password";

$hostname = "localhost";

//connection to the database

$Connect = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

echo "Connected to MySQL";

//select a specific database

$dbSelect = mysql_select_db("dbName", $dbConnect)

or die("Could not select dbName");

?>

Connecting to PDO Databases

BCS&BIT 2.2- Mr.Araka Page 72


PDO stands for PHP Data Objects and is a consistent way to access databases, which promises much
easier portable code. PDO is more like a data access layer which uses a unified API rather than an
abstraction layer. The syntax for connecting to a database using PDO is:

$username = "your_name";

$password = "your_password";

$hostname = "localhost";

// try to create connection

try {

$dbConnect = new PDO("mysql:host=$hostname;dbname=myDB", $username, $password);

// set the PDO error mode to exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Connected successfully";

// show an error if the connection was unsuccessful

catch(PDOException $e) {

echo "Connection failed: " . $e->getMessage();

Closing a Connection

The connection will be closed automatically when the script ends. To close the connection before, use

the mysql_close() function:

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

die(“*** Connection FAILED***”);

} else {echo "*** Connection Succeeded ***";}

BCS&BIT 2.2- Mr.Araka Page 73


// some code

mysql_close($con);

?>

PHP FORM HANDLING

Sample application development and database intergration

Config.php

<?php

$dbuser="root";

$dbpass="";

$host="localhost";

$dbname = "test";

$mysqli = new mysqli($host, $dbuser, $dbpass, $dbname);

?>

Users table structure

Index.php

BCS&BIT 2.2- Mr.Araka Page 74


<?php

include_once('config.php');

//Coding For Signup

if(isset($_POST['signup']))

//Getting Values

$fname=$_POST['fullname'];

$email=$_POST['email'];

$mobile=$_POST['mobilenumber'];

$pass=$_POST['password'];

//Checking email id exist

$result ="SELECT count(*) FROM tblusers WHERE EmailId=?";

$stmt = $mysqli->prepare($result);

$stmt->bind_param('s',$email);$stmt->execute();

$stmt->bind_result($count);

$stmt->fetch();

BCS&BIT 2.2- Mr.Araka Page 75


$stmt->close();

//if email already exist

if($count>0)

echo "<script>alert('Email id already associated with another account. Please try with diffrent
EmailId.');</script>";

// If email not exist

else {

$sql="INSERT into tblusers(FullName,EmailId,MobileNumber,Password)VALUES(?,?,?,?)";

$stmti = $mysqli->prepare($sql);

$stmti->bind_param('ssis',$fname,$email,$mobile,$pass);

$stmti->execute();

$stmti->close();

echo "<script>alert('User registration successful');</script>";

?>

BCS&BIT 2.2- Mr.Araka Page 76


Login.php

<?php session_start();

include_once('config.php');

//Coding For Signup

if(isset($_POST['login']))

//Getting Values

$email=$_POST['email'];

$pass=$_POST['password'];

$stmt = $mysqli->prepare( "SELECT FullName,id FROM tblusers WHERE (EmailId=? ||


Password=?)");

$stmt->bind_param('ss',$email,$pass);

$stmt->execute();

$stmt->bind_result($FullName,$id);

$rs= $stmt->fetch ();

$stmt->close();

BCS&BIT 2.2- Mr.Araka Page 77


if (!$rs) {

echo "<script>alert('Invalid Details. Please try again.')</script>";

else {

$_SESSION['fname']=$FullName;

$_SESSION['uid']=$id;

header('location:welcome.php');

?>

Welcome.php

<?php session_start();

//Validation login Session

if(strlen($_SESSION['uid'])==0)

header("Location:logout.php"); }

else{

?>

BCS&BIT 2.2- Mr.Araka Page 78


Validating a Web Form

The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:

Input Validation

BCS&BIT 2.2- Mr.Araka Page 79


Validate Form Data With PHP

The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.

When we use the htmlspecialchars() function;

We will also do two more things when the user submits the form:

Strip unnecessary characters (extra space, tab, newline) from the user input

data (with the PHP trim() function).Remove backslashes (\) from the user input data (with the
PHP stripslashes ()function

The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).We will name the function
test_input().

Now, we can check each $_POST variable with the test_input() function, and the script looks
like this:

EXAMPLE

<!DOCTYPE HTML>

<html>

<head>

<style>

.error {color: #FF0000;}

</style>

</head>

<body>

<?php

// define variables and set to empty values

$nameErr = $emailErr = $genderErr = $websiteErr = "";

$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

BCS&BIT 2.2- Mr.Araka Page 80


if (empty($_POST["name"])) {

$nameErr = "Name is required";

} else {

$name = test_input($_POST["name"]);

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} else {

$email = test_input($_POST["email"]);

if (empty($_POST["website"])) {

$website = "";

} else {

$website = test_input($_POST["website"]);

if (empty($_POST["comment"])) {

$comment = "";

} else {

$comment = test_input($_POST["comment"]);

if (empty($_POST["gender"])) {

$genderErr = "Gender is required";

} else {

$gender = test_input($_POST["gender"]);

BCS&BIT 2.2- Mr.Araka Page 81


}

function test_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<h2>PHP Form Validation Example</h2>

<p><span class="error">* required field.</span></p>

<form method="post" action="">

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

<span class="error">* <?php echo $nameErr;?></span>

<br><br>

E-mail: <input type="text" name="email">

<span class="error">* <?php echo $emailErr;?></span>

<br><br>

Website: <input type="text" name="website">

<span class="error"><?php echo $websiteErr;?></span>

<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>

<br><br>

Gender:

<input type="radio" name="gender" value="female">Female

<input type="radio" name="gender" value="male">Male

BCS&BIT 2.2- Mr.Araka Page 82


<span class="error">* <?php echo $genderErr;?></span>

<br><br>

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

</form>

</body>

</html>

Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has
been submitted - and it should be validated. If it has not been submitted, skip the validation and
display a blank form.

However, in the example above, all input fields are optional. The script works fine even if the
user does not enter any data.

The next step is to make input fields required and create error messages if needed.

BCS&BIT 2.2- Mr.Araka Page 83

You might also like