0% found this document useful (0 votes)
12 views110 pages

Introduction to PHP and Web Technology

This document provides an introduction to PHP, detailing its features, capabilities, and the basic concepts of web technology, including the Internet, WWW, HTTP, URLs, and web servers. It explains how PHP scripts are executed on the server, the characteristics of PHP, and the development environment needed for PHP applications. Additionally, it covers creating and running PHP scripts, handling errors, and mixing PHP with HTML for dynamic web content.
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)
12 views110 pages

Introduction to PHP and Web Technology

This document provides an introduction to PHP, detailing its features, capabilities, and the basic concepts of web technology, including the Internet, WWW, HTTP, URLs, and web servers. It explains how PHP scripts are executed on the server, the characteristics of PHP, and the development environment needed for PHP applications. Additionally, it covers creating and running PHP scripts, handling errors, and mixing PHP with HTML for dynamic web content.
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

PAPER NAME: Web Technology UNIT: I

CLASS: III BCA

CHAPTER I
INTRODUCTION
What is PHP?
 PHP is an acronym for "PHP Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP costs nothing, it is free to download and use
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can restrict users to access some pages on your website
 PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free.
 PHP is easy to learn and runs efficiently on the server side
Characteristics of PHP
1. Performance

DEPARTMENT OF BCA Page 1


 Scripts written in PHP execute faster than those written in other scripting languages, with many
independent standards putting the language ahead of competing alternatives like JSP, [Link],
and Perl.
 The PHP 5.0 engine was completely redesigned with an optimized memory manager to improve
performance, and is noticeably faster than previous versions.
2. Portability
 PHP is available for UNIX, Microsoft Windows, Mac OS, and OS/2, and PHP programs are
portable between platforms.
 As a result, a PHP application developed on, say, Windows will typically run on UNIX without any
significant issues.
 This ability to easily undertake cross-platform development is a valuable one, especially when
operating in a multiplatform corporate environment or when trying to address multiple market
segments.
3. Simplicity of Use
 PHP is an extremely stylish programming language.
 Its syntax is clear and consistent, and it comes with thorough documentation for the 5000+
functions included with the core distributions.
 PHP is preferred as a rapid prototyping tool for Web-based applications.
4. Open Source
 PHP is an open-source project—the language is developed by a worldwide team of volunteers who
make its source code freely available on the Web, and it may be used without payment of licensing
fees or investments in expensive hardware or software.
 This reduces software development costs without affecting either flexibility or reliability.
5. Third-Party Application Support
 One of PHP‟s strengths has historically been its support for a wide range of different databases,
including MySQL, PostgreSQL, Oracle,

BASIC WEB CONCEPTS


What is Internet?
 The Internet is essentially a global network of computing resources.
 You can think about the Internet as a physical collection of routers and circuits as a set of shared
resources or even as an attitude about interconnecting and intercommunication.
 Some common definitions given in the past include:
 A network of networks based on the TCP/IP communications protocol.
 A community of people who use and develop those networks.

DEPARTMENT OF BCA Page 2


 A community of people who use and develop those networks.
Internet Based Services:
Some of the basic services available to Internet users are:
 Email: A fast, easy, and inexpensive way to communicate with other Internet users around the
world.
 Telnet: Allows a user to log into a remote computer as though it were a local system.
 FTP: Allows a user to transfer virtually every kind of file that can be stored on a computer from
one Internet-connected computer to another.
 Use net news: A distributed bulletin board that offers a combination news and discussion service
on thousands of topics.
 World Wide Web (WWW): A hypertext interface to Internet information resources.
What is WWW?
 This stands for World Wide Web.
 A technical definition of the World Wide Web is : all the resources and users on the Internet that are
using the Hypertext Transfer Protocol (HTTP).
 A broader definition comes from the organization that Web inventor Tim Berners-Lee helped
found, the World Wide Web Consortium (W3C):
 The World Wide Web is the universe of network-accessible information, an embodiment of human
knowledge.
 In simple terms, The World Wide Web is a way of exchanging information between computers on
the Internet, tying them together into a vast collection of interactive multimedia resources.
What is HTTP?
 This stands for HyperText Transfer Protocol. This is the protocol being used to transfer hypertext
documents that makes the World Wide possible.
 A standard web address such as [Link] is called a URL and here the prefix http
indicates its protocol
What is URL?
 URL stands for Uniform Resource Locator, and is used to specify addresses on the World Wide
Web. A URL is the fundamental network identification for any resource connected to the web (e.g.,
hypertext pages, images, and sound files).
A URL will have the following format

protocol://hostname/other_information

 The protocol specifies how information from the link is transferred.


 The protocol used for web resources is HyperText Transfer Protocol (HTTP).
 Other protocols compatible with most web browsers include FTP, telnet, newsgroups, and Gopher.

DEPARTMENT OF BCA Page 3


 The protocol is followed by a colon, two slashes, and then the domain name.
 The domain name is the computer on which the resource is located.
 Links to particular files or subdirectories may be further specified after the domain name.
 The directory names are separated by single forward slashes.
What is Website?
 Currently you are on our website [Link] which is a collection of various
pages written in HTML markup language.
 This is a location on the web where people can find tutorials on latest technologies. Similar way
there is millions of websites available on the web.
 Each page available on the Website is called a web page and first page of any web site is called
home page for that site.
What is Web Server?
 Every Web site sits on a computer known as a Web server.
 This server is always connected to the internet.
 Every Web server that is connected to the Internet is given a unique address made up of a series of
four numbers between 0 and 256 separated by periods.
 for example, [Link] or [Link].
 When you register a Web address, also known as a domain name, such as [Link] you
have to specify the IP address of the Web server that will host the site.
 We will see different type of Web servers in a separate chapter.
What is Web Browser?
 Web Browsers are software installed on your PC.
 To access the Web you need a web browsers, such as Netscape Navigator, Microsoft Internet
Explorer or Mozilla Firefox.
 Currently you must be using any sort of Web browser while you are naviating through my site
[Link].
 On the Web, when you navigate through pages of information this is commonly known as browsing
or surfing.
What is SMTP Server?
 This stands for Simple Mail Transfer Protocol Server.
 This server takes care of delivering emails from one server to another server.
 When you send an email to an email address, it is delivered to its recipient by a SMTP Server.
What is ISP?
 This stands for Internet Service Provider.

DEPARTMENT OF BCA Page 4


 They are the companies who provide you service in terms of internet connection to connect to the
internet.
 You will buy space on a Web Server from any Internet Service Provider.
 This space will be used to host your Web site.
What is HTML?
 This stands for HyperText Markup Language.
 This is the language in which we write web pages for any Website. Even the page you are reading
right now is written in HTML.
 This is a subset of Standard Generalized Mark-Up Language (SGML) for electronic publishing, the
specific standard used for the World Wide Web.
What is Hyperlink?
 A hyperlink or simply a link is a selectable element in an electronic document that serves as an
access point to other electronic resources.
 Typically, you click the hyperlink to access the linked resource. Familiar hyperlinks include
buttons, icons, image maps, and clickable text links.
What is DNS?
 DNS stands for Domain Name System.
 When someone types in your domain name, [Link], your browser will ask the Domain
Name System to find the IP that hosts your site.
 When you register your domain name, your IP address should be put in a DNS along with your
domain name. Without doing it your domain name will not be functioning properly.

BASIC DEVELOPMENT CONCEPTS

When developing a PHP application for the Web, the typical approach is to embed PHP code into one or
more standard HTML documents using special “tags,” or delimiters. Here‟s an example:
<html>
<head></head>
<body>
<div>
<?php echo sqrt(49); ?>
</div>
</body>
</html>
 From the preceding explanation, it should be clear that to get started building PHP applications,

DEPARTMENT OF BCA Page 5


your development environment must contain at least three components:
 A base operating system (OS) and server environment (usually Linux)
 A Web server (usually Apache on Linux or IIS on Windows) to intercept HTTP requests and either
serve them directly or pass them on to the PHP interpreter for execution
 A PHP interpreter to parse and execute PHP code, and return the results to the Web server
 There‟s also often a fourth optional but very useful component:
 A database engine (such as MySQL) that holds application data, accepts connections from the PHP
layer, and modifies or retrieves data from the database
 An important corollary of this approach is that the PHP code is executed on the server, and not on
the client browser.
 This allows Web developers to write program code that is completely independent of, and thus
impervious to, browser quirks—an important advantage over client-side scripting languages, such as
JavaScript, which often require complex logic to account for browser-specific differences.
 Further, because the code is all executed on the server and only the output is sent to the client, it is
impossible for users to see the source code of your PHP program—an important security advantage
over languages like JavaScript.

CREATING FIRST PHP SCRIPTS


Writing and Running the Script
 PHP scripts are merely plain-text files containing PHP instructions, sometimes combined with
other odds and ends—JavaScript, HTML, and so on.
 So, the simplest way to write a PHP script is to pop open your favorite text editor and create a file
DEPARTMENT OF BCA Page 6
containing some PHP code, as follows:

<?php
// this line of code displays a famous quotation
echo 'A horse! A horse! My kingdom for a horse!';
?>
 Save this file to a location under your Web server‟s document root, and name it [Link].
 Then, start up your Web browser, and browse to the URL corresponding to the file location.

The output of the [Link] script

UNDERSTANDING THE SCRIPT


 When you requested the script [Link], the Apache Web server received your request, recognized
that the file was a PHP script (by means of the .php file extension), and handed it off to the PHP
parser and interpreter for further processing.
 This PHP interpreter then read the instructions between the <?php ... ?> tags, executed them,
and passed the results back to the Web server, which in turn sent them back to your browser.
 The instructions in this instance consisted of a call to PHP‟s echo statement, which is responsible
for displaying output to the user; the output to be displayed is enclosed in quotation marks.
 Free-form comments can be incorporated within a PHP script via the same conventions used in
JavaScript.
 Single-line comments must be preceded by the // characters, while multiline comments must be
enclosed within a /* ... */ comment block.
 These comments are excluded from the output of the PHP script. Here are some examples:
<?php
DEPARTMENT OF BCA Page 7
// a single-line comment
?>
<?php
/* a multi-line
comment
block */
?>

Handling Script Errors


 The PHP parser has a sharp eye. If your code includes an error, it will—depending on the severity of
the error—either display a warning message or stop script execution at the point of error with a
notification of what went wrong.
 To deliberately generate an error, go back to the [Link] script you created earlier and drop in an
extra semicolon after the echo keyword, so that the script now looks like this:

<?php

// this line of code displays a famous quotation

echo ; 'A horse! A horse! My kingdom for a horse!';

?>

 The PHP parser is quick to catch errors in your code.

 The error message generated by the parser is quite helpful: it tells you what the error was, as well

as the line on which it occurred.

 This makes it fairly easy—in most cases—to locate and correct the error.

The output generated by PHP when it finds a script error

Mixing PHP with HTML

DEPARTMENT OF BCA Page 8


 When the PHP
parser reads a script, it executes only the code found between PHP tags; everything outside these
tags is ignored by the parser and returned “as is.”
 This makes it
extremely easy to embed PHP code within an HTML document to create Web pages that have all
the formatting bells and whistles of standard HTML but can additionally perform complex
calculations or read and manipulate data from external sources (such as databases or Web
services).
EXAMPLE:
"DTD/[Link]">
<html xmlns="[Link] xml:lang="en" lang="en">
<head>
<title>HTML Color Table</title>
<style type="text/css">
body{
font-family: Verdana sans-serif;
}
td {
border: solid 5px white;
}
</style>
</head>
<body>
<h2>Colors with HTML and PHP</h2>
<table>
<tr>
<td>Blue</td>
<td style="width:40px; background-color:#0000ff"></td>
</tr>
<tr>
td><?php echo 'Red'; ?></td>
<td style="width:40px;
background-color:<?php echo '#ff0000'; ?>"></td>
</tr>
<?php
DEPARTMENT OF BCA Page 9
// this row generated through PHP
echo "<tr>\n";
echo " <td>Green</td>\n";
echo " <td style=\"width:40px; background-color:#00ff00\"></td>\n";
echo "</tr>\n";
?>
</table>
</body>
</html>
 Save this script as [Link], and view it in your Web browser.
 You should see an HTML page containing a table with three rows and two columns, with one
column containing a color and the other its corresponding name

 A Web page containing colors and color codes, generated by mixing PHP with HTML

ESCAPING SPECIAL CHARACTERS


 PHP allows you to escape certain characters by earlier them with a backslash (\). There so-called
escape sequences include

Sequence What It Represents


\n a line feed character
\t a tab
\r a carriage return
\" a double quotation mark
\' a single quotation mark

 W
hen the parser encounters one of these escape sequences, it knows to replace it with the
corresponding value before sending it to the output device. Consider, for example, this line of

DEPARTMENT OF BCA Page 10


code:
<?php
echo "You said \"Hello\"";
?>

CHAPTER II

USING VARIABLES AND OPERATORS


STORING DATA IN VARIABLES
 A variable is simply a container that‟s used to store both numeric and non-numeric information.
Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have basic types - a variable does not know in advance whether it
will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 PHP variables are [Link], for example,

1. ASSIGNING VALUES TO VARIABLES


 A
ssigning a value to a variable in PHP is quite easy: use the equality (=) symbol, which also happens
to be PHP‟s assignment operator.
 T
his assigns the value on the right side of the equation to the variable on the left.
 To use a variable in a script, simply call it by name in an expression and PHP will replace it with its
value when the script is executed.
EXAMPLE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "DTD/[Link]">
<html xmlns="[Link] xml:lang="en" lang="en">
<head><title /></head>

DEPARTMENT OF BCA Page 11


<body>
<?php
// assign value to variable
$name = 'Simon';
?>
<h2>Welcome to <?php echo $name; ?>'s Blog!</h2>
</body>
</html>

 In this example, the variable $name is assigned the value 'Simon'. The echo statement is then
used to print the value of this variable to the Web page.
 You can also assign a variable the value of another variable, or the result of a calculation. The
following example demonstrates both these situations:
EXAMPLE:
<?php
// assign value to variable
$now = 2008;
// assign variable to another variable
$currentYear = $now;
// perform calculation
$lastYear = $currentYear - 1;
// output: '2007 has ended. Welcome to 2008!'
echo "$lastYear has ended. Welcome to $currentYear!";
?>

2. DESTROYING VARIABLES
 To destroy a variable, pass the variable to PHP‟s aptly named unset() function, as in the
following example:
<?php
// assign value to variable
$car = 'Porsche';
// print variable value
// output: 'Before unset(), my car is a Porsche'
echo "Before unset(), my car is a $car";

DEPARTMENT OF BCA Page 12


// destroy variable unset($car);
// print variable value
// this will generate an 'undefined variable' error
// output: 'After unset(), my car is a '
echo "After unset(), my car is a $car";
?>
3. INSPECTING VARIABLE CONTENTS
 PHP offers the var_dump() function, which accepts a variable and X-rays it for you.
Here‟s an example:
<?php
// define variables
$name = 'Fiona';
$age = 28;
// display variable contents var_dump($name);
var_dump($age);
?>

UNDERSTANDING PHP’S DATA TYPES


 The values assigned to a PHP variable may be of different data types, ranging from simple string
and numeric types to more complex arrays and objects.
 PHP has a total of eight data types which we use to construct our variables:
 Integers: are whole numbers, without a decimal point, like 4195.
 Doubles: are floating-point numbers, like 3.14159 or 49.1.
 Booleans: have only two possible values either true or false.
 NULL: is a special type that only has one value: NULL.
 Strings: are sequences of characters, like 'PHP supports string operations.'
 Arrays: are named and indexed collections of other values.
 Objects: are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
 Resources: are special variables that hold references to resources external to PHP (such as
database connections).
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 so:

DEPARTMENT OF BCA Page 13


EXAMPLE:
$int_var = 12345;
$another_int = -12345 + 12345;

2. Doubles:
 They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code:
EXAMPLE:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);

It produces the following browser output:


2.28888 + 2.21112 = 4.5

3. Boolean:
 They have only two possible values either true or false.
 PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which
can be used like so:
EXAMPLE:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");

4. NULL:
 NULL is a special type that only has one value: NULL.
 To give a variable the NULL value, simply assign it like this:

EXAMPLE:
$my_var = NULL

5. Strings:
 They are sequences of characters, like "PHP supports string operations".

DEPARTMENT OF BCA Page 14


 Following are valid examples of string
EXAMPLE:
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

SETTING AND CHECKING VARIABLE DATA TYPES


 Unlike other programming languages, where a variable‟s data type must be explicitly defined by the
programmer, PHP automatically determines a variable‟s data type from the content it holds.
 And if the variable‟s content changes over the duration of a script, the language will automatically
set the variable to the appropriate new data type.
EXAMPLE:
<?php
$whoami = 'Sarah'; // define string variable

gettype($whoami); // output: 'string' echo

$whoami = 99.8; // assign new integer value to variable

gettype($whoami); // output: 'double' echo

unset($whoami); // destroy variable

echo gettype($whoami); // output: 'NULL'

?>
 This example introduces PHP‟s gettype() operator, which is a handy little tool for finding out
the type of a particular variable.
 As the script output demonstrates, the variable $whoami begins life as a string, assigned the value
'Sarah'.
 It‟s then assigned the number 99.8, which automatically converts it to a floating-point variable.
 Following this, the variable is de-initialized with the unset() method, which removes its value
and turns it into a NULL.
 PHP has been the invisible hand behind each of these conversions, internally resetting the data
type of $whoami from string to floating-point to null.
 Casting is a technique commonly used by Java programmers; to use it, simply specify the desired
data type in parentheses on the right side of the assignment equation.
 Consider the following example, which illustrates turning a floating-point value into an integer
value:
EXAMPLE:
<?php
DEPARTMENT OF BCA Page 15
$speed = 501.789; // define floating-point variable

$newSpeed = (integer) $speed; // cast to integer

$newSpeed; // output: 501


echo
?>

 In addition to the gettype() function, PHP includes a number of more specialized functions, to
test if a variable is of a specific type.
FUNCTION PURPOSE
is_bool() Tests if a variable holds a Boolean value
is_numeric() Tests if a variable holds a numeric value
is_int() Tests if a variable holds an integer
is_float() Tests if a variable holds a floating-point
is_string() Tests
valueif a variable holds a string value
is_null() Tests if a variable holds a NULL value
is_array() Tests if a variable is an array
is_object() Tests if a variable is an object

PHP Functions to Test Variable Data Types

USING CONSTANTS
 Constants are PHP containers for values that remain constant and never change.
 They‟re mostly used for data that is known well in advance and that is used, unchanged, in multiple
places within your application.
 Constants are defined using PHP‟s define() function, which accepts two arguments: the name of
the constant, and its value.
 Constant names must follow the same rules as variable names, with one exception: the $ prefix is
not required for constant names.
Here‟s an example of defining and using a constant in a script:
EXAMPLE:
<?php
define ('PROGRAM', 'The Matrix'); // define constants
define ('VERSION', 11.7); // use constants
// output: 'Welcome to The Matrix (version 11.7)'
echo 'Welcome to „ . PROGRAM . (version . VERSION . ')';
?>
MANIPULATING VARIABLES WITH OPERATORS
 Variables are simply containers for information.

DEPARTMENT OF BCA Page 16


 In order to do anything useful with them, you need operators.
 Operators are symbols that tell the PHP processor to perform certain actions.
 For example, the addition (+) symbol is an operator that tells PHP to add two variables or values,
while the greater-than (>) symbol is an operator that tells PHP to compare two values.
 PHP supports more than 50 such operators, ranging from operators for arithmetical operations to
operators for logical comparison and bitwise calculations.
Performing Arithmetic Operations

Operator Description
+ Add
- Subtract
* Multiply
/ Divide and return quotient
% Divide and return modulus
Common Arithmetic Operators
EXAMPLE:
<?php
$x = 10; // define variables
$y = 5;
$z = 3;
$sum = $x + $y; // add
echo "$x + $y = $sum\n";
$diff = $x - $y; // subtract
echo "$x - $y = $diff\n";
$product = $x * $y; // multiply
echo "$x * $y = $product\n";
$quotient = $x / $y; // divide and get quotient
echo "$x / $y = $quotient\n";
$modulus = $x % $y; // divide and get modulus
echo "$x % $y = $modulus\n";
?>

Concatenating Strings
To combine strings, use PHP‟s concatenation operator, which happens to be a period (.). The
following example illustrates:
EXAMPLE:
<?php

DEPARTMENT OF BCA Page 17


$country = 'England'; // define variables
$city = 'London';
// combine into single string
// output: 'Welcome to London, the coolest city in all of England'
echo 'Welcome to ' . $city . ', the coolest city in all of ' .$country‟;
?>
Comparing Variables
 PHP lets you compare one variable or value with another via its wide range of comparison
operators,
<?php
$p = 10; // define variables
$q = 11;
$r = 11.3;
$s = 11;

// test if $q is greater than $p


// returns true
echo ($q > $p);

// test if $q is less than $p


// returns false
echo ($q < $p);

// test if $q is greater than or equal to $s


// returns true
echo ($q >= $s);

// test if $r is less than or equal to $s


// returns false
echo ($r <= $s);
// test if $q is equal to $s
// returns true
echo ($q == $s);

// test if $q is equal to $r

DEPARTMENT OF BCA Page 18


// returns false
echo ($q == $r);
?>

Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type
Common Comparison Operators
Performing Logical Tests
 When building complex conditional expressions, PHP‟s three most commonly used logical
operators, listed in
Operator Description

&& AND

|| OR

! NOT
EXAMPLE:
<?php
// define variables
$price = 100;
$size = 18;

// logical AND test


// returns true if both comparisons are true
// returns true here
echo ($price > 50 && $size < 25);

// logical OR test
// returns true if any of the comparisons are true
// returns false here
echo ($price > 150 || $size > 75);
// logical NOT test
// reverses the logical test

DEPARTMENT OF BCA Page 19


// returns false here
echo !($size > 10);
?>
Other Useful Operators
 There are a few other operators that tend to come in handy during PHP development.
 First, the addition-assignment operator, represented by the symbol +=, lets you simultaneously add
and assign a new value to a variable

Operator Description
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign quotient
%= Divide and assign modulus
.= Concatenate and assign (strings only)

Here are examples of these in action:


<?php
// define variables
$count = 7;
$age = 60;
$greeting = 'We';

// subtract 2 and re-assign new value to variable


// equivalent to $count = $count - 2
// output: 5
$count -= 2;
echo $count;

// divide by 5 and re-assign new value to variable


// equivalent to $age = $age / 5
// output: 12
$age /= 5;
echo $age;

// add new string and re-assign new value to variable


// equivalent to $greeting = $greeting . 'lcome!'
// output: 'Welcome!'
DEPARTMENT OF BCA Page 20
$greeting .= 'lcome!';
echo $greeting;
?>
**************************** UNIT I COMPLETED**********************************
QUESTION BANK-UNIT 1
2 MARKS
1. What is php?
2. What is php file?
3. What php file can do?
4. List the characteristics of php.
5. What is internet?
6. What is www?
7. What is http?
8. What is URL?
9. What is website?
10. What is web server?
11. What is web browser?
12. What is SMTP server?
13. What I s ISP?
14. What is HTML?
15. What is Hyperlink?
16. What is DNS?
17. How will you create first php file?
18. Write few points about comment lines?
19. How will you handle php script errors?
20. Write notes on escaping special character>
21. What is php variable?
22. How will you assign a variable in php?
23. How will you destroy a variable in php?
24. List the data types of php.
25. What are constants?
26. List out operators available in php.

5 MARKS AND 10 MARKS


1. Explain the characteristics of php.
2. Discuss about basic web concepts.
3. What are the basic development concepts?
4. How will you create a first php file and explain it?
5. Write a notes on storing data‟s in variables.
6. Explain about php data types.
7. Write short notes on setting and checking variables in data types.
8. Explain about php operators.

DEPARTMENT OF BCA Page 21


UNIT-II

CONTROLLING PROGRAM FLOW


The PHP programs you saw in the preceding chapter were straight forward: they accepted one
or more input values, performed calculations or comparisons with them, and returned a result.

I. WRITING SIMPLE CONTITIONAL STATEMENTS


In addition to storing and retrieving value in variables, PHP also lets programmers evaluate
different conditions during the course of a program and take decisions based on whether these conditions
evaluate to true or false. These conditions, and the actions associated with them, are expressed by means of a
programming construct called a conditional statement. PHP supports different types of conditional statements,
each one intended for a particular use.

i)The if statement
The simplest of PHP’s conditional statements is the if statement. This works much like the
English-language statement, “if X happens, do Y.” here’s a simple example, which contains a conditional
statement that checks if the value of the $number variable is less than 0 and prints a notification message if
so.
Example:

<?php
// if number is less than zero
//print message
$number = - 88;
If ($number < 0) {
echo ‘That number is negative’ ;}
?>

The key to the if statement is thus the condition to be evaluated, which is always enclosed in
parentheses.
ii) The if-else statement
The if statement is quite basic: it only lets you define what happens when the conditions specified
evaluates to true. But PHP also offers the if –else statement, an improved version of the if construct that
allows you to define an alternative set of action that the program should take when the condition specified
evaluates to false. In English, this statement would read, “if X happens, do Y; otherwise, do Z.”
OPERATOR DESCRIPTION
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type

Example:
<?php
//change message depending on whether
//number is less than zero or not
$number =-88;
If ($number<0)
{echo ‘that number is negative’;}
Else
{echo ‘that number is either positive or zero’;}
?>
Here, an if –else statements is used to account for two possible outcomes: a number less than
zero, and all other number.

II. WRITING MORE COMPLEX CONDITIONAL STATEMENTS


The if –else statement lets you define actions for two eventualities: a true condition and a false
conduction. The if -elseif-else statement and the switch –case statements.

i)THE IF -ELSEIF-ELSE STATEMENT


The if -elseif-else statement lets you chain together multiple if –else statements, thus allowing the
programmer to define actions for more than just two possible outcomes. Consider the following examples ,
which illustrates its use:

<?php
//handle multiple possibilities
//define a different message for each day $today=’Tuesday’;
If ($today == ‘Monday’)
{
Echo ‘Monday\’s child is fair of face. ’;}
Elseif ($today == ‘Tuesday’) {
echo ‘Tuesday\ ‘s child is full of grace. ‘;}
elseif ($today == ‘Wednesday’){
echo ‘Wednesday\ ‘s child is full of woe.’ ;}
elseif ($today == ‘Thursday’){
echo ‘Thursday\ ‘s child has far to go.’ ;}
elseif ($today == ‘Friday’){
echo ‘Thursday\ ‘s child is loving and giving.’ ;}
elseif ($today == ‘Saturday’){
echo ‘Thursday\ ‘s child works hard for a living.’ ;}
else{ echo ‘No information available for that day’;}
?>
Here, the program will output a different message for each day of the week (as set in the $today variable).

ii)THE SWITCH-CASE STATEMENT

An alternative to the if-elseif-else statement is the switch-case statement, which does almost the
same thing: it tests a variable against a series of values until it finds a match, and then executes the code
corresponding to that match. Consider the following code listing, which is equivalent to the preceding one:

<?php
// handle multiple possibilities
// define a different message for each day
$today = ‘Tuesday’ ;
Switch ($today)
{
Case ‘Monday’ :
echo ‘Monday\ ‘s child is fair of face. ‘ ;
break;
Case ‘Tuesday’ :
echo ‘Tuesday\ ‘s child is full of grace. ‘ ;
break;
Case ‘Wednesday’ :
echo ‘Wednesday\ ‘s child is full of woe. ‘ ;
break;
Case ‘Thursday’ :
echo ‘Thursday\ ‘s child is far to go. ‘ ;
break;
Case ‘Friday’ :
echo ‘Friday\ ‘s child is loving and giving. ‘ ;
break;
Case ‘Saturday’ :
echo ‘Saturday\ ‘s child is works hard for a living. ‘ ;
break;
default:
echo ‘No information available for that day’;
}
?>

The switch-case construct differs from the if-elseif-else construct in one important way. Once PHP finds
a case statement that evaluates to true, it executes not only the code corresponding to that case statement, but
also the code for all subsequent case statements. If this is not what you want, add a break statement to the end
of each case block (as is done in the previous listing) to tell PHP to break out of the switch-case statement
block once it executes the code corresponding to the first true case.
Notice also the ‘default’ case: as the name suggests, this specifies the default set of actions PHP should
take if none of the other cases evaluate to true. This default case, like the else branch of the if-elseif-else block,
is very useful as a “catch-all” handler for unforeseen situations.

iii) COMBINING CONDITIONAL STATEMENTS

PHP allows one conditional statement to be nested within another, to allow for more complex decision-
making. To illustrate this, consider the following listing:

<?php
// for employees with annual comp <= $15000
// those with a rating >= 3 get a $3000 bonus
If ($rating >= 3) {
If ($salary < 15000) {
$bonus = 5000 ;
}
}
else {
if ($salary < 15000)
{
$bonus = 3000 ;
}
}
?>
You can also combine conditional statements by using logical operators, such as the && or || operator. You
learned about logical operators in the preceding chapter; Table 3-2 quickly recaps the list.
Here’s an example of how these logical operators can be used with a conditional statement:

<?php
$year = 2008;
// leap years are divisible by 400
// or by 4 but not 100
If (($year % 400 == 0) || (($year % 100 !=0) && ($year % 4 == 0)))
{
echo “$year is a leap year.”;
}
?>

III. REPEATING ACTIONS WITH LOOPS

Like any good programming language, PHP also supports loops ---essentially, the ability to
repeat a series of actions until a prespecified condition is fulfilled. Loops are an important tool that
help in automating repetitive tasks within a program. PHP supports four different types of loops:
The while loop
The do-while loop
The for loop
The for each loop
Three of which are discussed in the following sections (the fourth type is explained in the next chapter).

i)THE WHILE LOOP

The easiest type of loop to understand is the while loop, which repeats continuosly while a prespecified
condition is true. Here’s an example, which uses a loop to repeatly print an ‘X’ to the output page.

<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
While ($counter < 10)
{
echo ‘x’ ;
$counter++;
}
?>
ii)THE DO-WHILE LOOP
With a while loop, the condition to be evaluated is tested at the beginning of each loop iteration. There’s
also a variant of this loop, the do-while loop, the do-while loop, which evaluates the condition at the end of
each loop iteration.
<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
do
{
echo ‘x’ ;
$counter++;
}
While ($counter < 10);
?>

iii)THE FOR LOOP

The while and do-while loops are firely simple: they repeat for so long as the specified condition remains
true. But PHP also supports a more sophisticated type of loop, the for loop, which is useful when you need to
execute a set of statements a specific number of times.

The best way to understand a for loop is by looking at some code. Here’s simple example,

Which lists the numbers between 1 and 10.

<?php
// repeat continuously until counter becomes 10
// output: ‘XXXXXXXXX’
For ($x=1; $x<10; $x++)
{
Echo “$x”;}
?>
 The first of this is an assignment expression, which initialize the loop counter to a specific values-
-- in this case, assigning the value 1 to the variable $x.
 The second is a conditional expression, which must evaluate to either true or false; the loop will
continue to execute so long as this condition remains true. Once the condition becomes false, the
loop will stop executing.
 The third is again an assignment expression, which is executed at the end of each loop iteration,
and which updates the loop counter with a new value – in this case, adding 1 to the value of $x.

<?php
// generate ordered list of 6 times
echo “<01>”;
for ($x=1; $x<7; $x++)
{
echo “<li>Item $x</li>”;
}
echo “ </01>”;
?>

iv)COMBINING LOOPS

Just as with conditional statements, it’s also possible to nest one loop inside another. To illustrate,
consider the next example, which nests one for loop inside another loop to dynamically generate an HTML
table.

Example:

<html>
<head>
<title></title>
</head>
<body>
<?php
// generate an HTML table
// 3 rows, 4 columns
echo “<table border= \”1\”>”;
for ($row =1 ; $row<4; $row++)
{
echo “<tr>”;
for ($col =1; $col<5; $col++)
{
echo “<td>Row $row, column $col< /td>”;
}
echo “</tr>”;
}
echo “</table>”;
?>
</body>
</html>

Output:

Row 1, Column 1 Row 1, Column 2 Row 1, Column 3 Row 1, Column 4


Row 2, Column 1 Row 2, Column 2 Row 2, Column 3 Row 2, Column 4
Row 3, Column 1 Row 3, Column 2 Row 3, Column 3 Row 3, Column 4

V)INTERRUPTING AND SKIPPING LOOPS

While on the topic of loops, it’s interesting to discuss two PHP statements that allow you to either
interrupt a loop or skip a particular iteration of a loop. PHP’s break statement is aptly named: it allows you to
break out of a loop at any point

Example:

<?php
$count = 0;
// loop 5 times
While ($count <= 4)
{
$count++;
// when the counter hits 3
// breakout of the loop
if ($count == 3)
{
Break;
}
echo “this is iteration #$count <br/>”;
}
?>
Example: Break and continue
<?php
$count = 0;
//loop 5 times
While ($count <= 4)
{
$count++;
// when the counter hits 3
// skip to the next iteration
if($count == 3)
{
Continue;
}
echo “this is iteration #$count <br/>”;
}
?>

IV. WORKING WITH STRING AND NUMEERIC FUNCTIONS


PHP’s data types, including its operators for string and number manipulation. But PHP lets you
do a lot more than simply concatenate string and add values.

i)USING STRING FUNCTIONS

PHP has over 75 built-in-string manipulation functions, supporting operation ranging from string
repetition and reversal to comparison and search- and – replace. Table 3-3 lists some of these functions.

a) Checking for empty strings


The empty( ) function returns true if a string variable is “empty”. Empty string variables are
those with the values ‘ ‘ ,0, ‘0’, or NULL. The empty ( ) function also returns true when used with a
non-existent variable. Here are some examples:

<?php
// test if string is empty
// output:true
$str=’’;
echo (boolean) empty ($str);
// output:true
$str=null;
echo (boolean) empty ($str);
// output:true
$str=’0’;
echo (boolean) empty ($str);
// output:true
Unset ($str);
echo (boolean) empty ($str);
?>
FUNCTION WHAT IT DOES
Empty( ) Tests if a string is empty
Strlen( ) Calculates the number of character in a string
strrev( ) Reverses a string
str_repeat Repeats a string
substr() Retrieves a section of a string
strcmp() Compares two string
str_word_count() Calculates the number of words in a string
str_replace() Replaces parts of a string
trim() Removes leading and trailing whitespace from a string
strtolower() Lowercases a string
strtoupper() Uppercases a string
ucfirst() Uppercases the first character of a string
ucword() Uppercases the first character of every word of string
addslahes() Escapes special characters in a string with backslashes
stripslashes() Remove backslashes from a string
htmlentities() Encodes HTML within a string
htmlspecialchars() Encodes special HTML characters within a string
nl2br() Replaces line breaks in a string with <br/> elements
html_entity_decode() Decodes HTML entities within a string
htmlspecialchars_decode() Decodes special HTML characters within a string
strip_tags() Removes PHP and HTML code from a string

b) Reversing and Replacing Strings

The strlen() function returns the number of characters in a string. Here’s an example of it in
action:

<?php
// calculate length of string
// output: 17
$str = ‘welcome to Xanadu’;
echo strlen($str);
?>
Reversing a string is as simple as calling the strrev() function, as in the next listing:

<?php
//reverse string
//output: ‘pets llams enO’
$str = ‘one small step’;
echo strrev($str);
?>
In case you need to repeat a string, PHP offers the str_repeat() function, which accepts two arguments----
the string to be repeated, and the number of times to repeat it. Here’s an example:

<?php
// repeat string
// output: ‘yoyoyo’
$str = ‘yo’;
echo str_repeat($str, 3);
?>
c) Working with Substrings
PHP also allows you to slice a string into smaller parts with the substr() function, which accepts three
arguments: the original string, the position (offset) at which to start slicing, and the number of characters to
return from the starting position. The following listing illustrates this in action:

<?php
// extract substring
// output: ‘come’
$str = ‘welcome to nowhere’;
echo substr($str, 3, 4);
?>
d) Comparing, Counting, and Replacing Strings
If you need to compare two strings, the strcmp() function performs a case-sensitive comparison of two
strings, returning a negative value if the first is “less” than the second,a positive value if it’s the other way
around, and zero if both strings are “equal.” Here are some examples of how this works:

<?php
// compare strings
$a = “hello”;
$b =”hello”;
$c =”hello”;
Output:0
echo strcmp($a, $b);
Output: 1
echo strcmp($a, $c);
?>
PHP’s str_word_count() function provides an easy way to count the number of words in a string. The
following listing illustrates its use:

<?php
//count words
//Output: 5
$str = “the name’s Bond, James Bond”;
echo str_word_count($str);

?>

If you need to perform substitution within a string. PHP also has the str_replace() function, designed
specifically to perform find-and-replace operations. This function accepts three arguments: the search term,
the replacement term, and the string in which to perform the replacement. Here’s an example:
<?php
//replace ‘@’ with ‘at’
Output:
‘john at [Link]’
$str =’john@[Link]’;
Echo str_replace(‘@’ , ‘at’, $str);
?>
e) Formatting Strings
PHP’s trim() function can be used to remove leading or travelling whitespace from a string; this is
quite useful when processing data entered into a Web form. Here’s an example:

<?php
//remove leading and trailing whitespace
//output ‘a b c’
$str = ‘a b c ‘;
echo trim($str);
?>
Changing the case of a string is as simple as calling the strtolower() or strtoupper() function, as
illustrated in the next listing:
<?php
//change string case\
$str = ‘yabba dabba doo’;
//output: ‘yabba dabba doo’
Echo strtolower($str);
//output: ‘YABBA DABBA DOO’
echo strtoupper($str);
?>
You can also uppercase the first character of a string with the ucfirst() a function, or format String in
“word case” with the ucwords() function. The following listing demonstrates both these functions:

<?php
//change string case
$str = ‘the yellow Brigands’;
//output: ‘The Yellow Brigands’
echo ucwords($str);
//output: ‘ The yellow brigands’
echo ucfirst($str);
?>

f) Working with HTML Strings


PHP also has some functions exclusively for working with HTML strings. First up, the addslashes()
function, which automatically escapes special characters in a string with backslashes. Here’s an example:
<?php
// escape special characters
// output: ‘you\’re awake, aren\’t you?’
$str = “you’re awake , aren’t you?”;
echo addslashes($str);\
?>
You can reverse the work done by addslashes() with the aptly named striplashes() function, which
removes all the backslashes from a string. consider the following example, which illustrates:
<? php
//replace with HTML entities
//output: ‘&lt;div width=&quot;&gt;
// this is a div&lt;/div&gt;’
$html = ‘<div width=”200”>This is a div</div>’;
echo htmlentities($html);
//replace line breaks with <br/>s
//output: ‘This is a bro<br />
$lines = ‘This is a bro Ken line’;
echo n12br($lines);
?>
You can reverse the effect of the htmlentities() and htmlspecialchars() functions with the
html_entitiy_decode() and htmlspecialchars_decode() functions.
Finally, the strip_tags() function searches for all HTML and PHP code within a string and removes it to
generate a “clean” string. Here’s an example:

<?php
// string HTML tags from string
//output: ‘please log in again’
$html =’<div width=”200”>please <strong>log in again</strong></div>’;
echo strip_tags($html);
?>

ii)USING NUMERIC FUNCTIONS


Don’t think that PHP’s is limited to strings only: the language has over 50 built-in functions for working
with numbers, ranging fro simple formatting functions to functions for arithimetic, logarithmic, and
trigonometric manipulations. Table 3-4 lists some of these functions.

FUNCTION WHAT IT DOES


Ceil() Rounds a number up
Floor() Rounds a number down
Abs() Finds the absolute value of a number
Pow() Raises one number to the power of another
Log() Finds the algorithm of a number
Exp() Finds the exponent of a number
Rand() Generates a random number
Bindec() Converts a number from binary to decimal
Decbin() Converts a number from decimal to binary
Decoct() Converts a number from decimal to octal
Hexdec() Converts a number from decimal to hexadecimal
Octdec() Converts a number from octal to decimal
Number_format() Formats a number with grouped thousands and decimals
Printf() Formats a number using a custom specification

TABLE 3-4 COMMON PHP NUMERIC FUNCTIONS

a. Doing Calculus

A common task when working with numbers involves rounding them up and down. PHP offers the ceil()
and floor() functions for this task, and they’re illustrated in the next listing:

<?php
//round number up
//output:19
$num = 19.7;
echo floor($num);
//round number down
//output:20
echo ceil($num);
?>
There’s also the abs() function which returns the absolute value of a number. Here’ s an example:
<?php
//return absolute value of number
//output:19.7
$num = -19.7;
echo abs($num);
?>
The pow() function returns the value of a number raised to the power of another:
<?php
//calculate 4 ^ 3
//output: 64
echo pow(4,3);
?>

The log() function calculates the natural or base-10 logarithm of a number, while the exp() function
calculates the exponent of a number. Here’s an example of both in action:

<?php
//calculate natural log of 100
//output: 2.30258509299
echo log(10);
//calculate exponent of 2.30258509299
//output: 9.99999999996
echo exp(2.30258509299);
?>
b. Generating Random Numbers
Generating random numbers with PHP is pretty simple too: the language’s built-in rand() function
automatically generates a random integer greater than 0. You can constrain it to a specific number range by
providing optional limits as arguments. The following example illustrates:

<?php
//generate a random number
echo rand();
//generate a random number between 10 and 99
echo rand (10,99);
?>
c. Converting Between Number Bases
PHP comes with built-in functions for converting between binary, decimal, octal, and hexadecimal bases.
Here’s an example which demonstrates the bindec() , decbin(), decoct(), dechex(), hexdec(), and octdec()
functions in action:

<?php
//convert to binary
//output: 1000
echo decbin(8);
//convert to hexodecimal
//output: 8
echo dechex(8);
//convert to octal
//output: 10
echo decoct(8);
//convert from octal
//output: 8
echo octdec(10);
//convert from hexodecimal
//output: 101
echo hexdec(65);
//convert from binary
//output: 8
echo bindec(1000);
?>

d. Formatting Numbers
When it comes to formatting numbers, PHP offers the number_format() function, which accept four
arguments: the number to be formatted, the number of decimal places to display , the character to use instead
of a decimal point, and the character to use to separate grouped thousands(usually a comma). Consider the
following example, which illustrates:

<?php
//format number (with defaults)
//output: 1,106,483
$sum = 1106482.5843;
echo number_format($num);
//format number (with custom separators)
//output: 1?106?482*584
Echo number_format($num,3, ‘*’ , ‘?’ );
?>
For more control over number formatting, PHP offers the printf() and sprintf() functions. These
functions, though very useful, can be intimidating to new users, and so that best way to understand them is
with an example.
SPECIFIER WHAT IT MEANS
%s String
%d Decimal number
%x Hexadecimal number
%o Octal number
%f Floating-point number

Table 3-5 Format Specifiers for the printf() and sprint() functions

Consider the nex listing, which shows them in action:

<?php
// format as decimal number
//output: 00065
printf(“%05d”,65);
//format as floating-point number
//output: 00239.000
printf(“%09.3f”,239);
//format as octal number
//output: 10
printf(“%40”, 8);
//format number
//incorporate into string
//output: ‘ I see 8 apples and 26.00 oranges’
prinf("I see %4d apples and %4.2f oranges”, 8,26);
?>
UNIT III

CHAPTER I
WORKING WITH ARRAYS
PHP Arrays:
 An array is a data structure that stores one or more similar type of values in a single value. For
example if you want to store 100 numbers then instead of defining 100 variables its easy to define
an array of 100 length.
 There are three different kinds of arrays and each array value is accessed using an IDc which is
called array index.
 Numeric array- An array with a numeric index. Values are stored and accessed in linear fashion
 Associative array- An array with strings as index. This stores element values in association
with key value rather than in a strict linear index order.
 Multidimensional array-An array containing one or more arrays and values are accessed using
multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be pre presented by numbers.
By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array()function to create array. This function is explained in function reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";

DEPARTMENT OF BCA, METTALA Page 1


$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one Value is two Value is
three Value is four Value is five
Associative Arrays
 The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index.
 Associative array will have their index as string so that you can establish a strong association
between key and values.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000, "qadir" => 1000, "zara" => 500
);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";

DEPARTMENT OF BCA, METTALA Page 2


$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high Salary of qadir is
medium Salary of zara is low

Multidimensional Arrays
 A multi-dimensional array each element in the main array can also be an array. And each element
in the sub-array can be an array, and soon.
 Values in the multi-dimensional array are accessed using multiple indexes.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
<html>
<body>
<?php
$marks = array(
"mohammad" => array
(
"physics" => 35, "maths" => 30, "chemistry" => 39
),
"qadir" => array
(
"physics" => 30, "maths" => 32, "chemistry" => 29
),
"zara" => array
(

DEPARTMENT OF BCA, METTALA Page 3


"physics" => 31, "maths" => 22, "chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara
STORING DATA IN ARRAYS
Array variables are “special,” because they can hold more than one value at a time.
example:
<?php
//definearray
$fruits= array('apple','banana','pineapple','grape');
?>
AssigningArrayValues
 PHP’s rules for naming array variables are the same as those for regular variables: variable names
must be preceded with a dollar ($)symbol and must begin with a letter or underscore character,
optionally followed by more letters, numbers, or underscore characters.
 Punctuation characters and spaces are not allowed within array variable names.
 There are two ways of assigning values to it.
 The first is the method you saw in the preceding section, where the values are all assigned at once,
separated with commas. This method creates a standard, number- indexed array.
example:
<?php
//definearray

DEPARTMENT OF BCA, METTALA Page 4


$cars= array(
'Ferrari',
'Porsche',
'Jaguar',
'Lamborghini',
'Mercedes'
);
?>
 The second way to create such an array is to set values individually using index notation. Here’s
an example, which is equivalent to the preceding one:
<?php
//define array
$cars[0]= 'Ferrari';
$cars[1]= 'Porsche';
$cars[2]= 'Jaguar';
$cars[3]= 'Lamborghini';
$cars[4]= 'Mercedes';
?>
 You can also use both these techniques with associative arrays.
 To assign all the values of such an array in a single statement, set a key for each value and
link the two using the =>connector, remembering to separate each key-value pair with
commas.
example:
<?php
//define array
$data= array(
'username'=>'john',
'password'=>'secret',
'host'=>'[Link]'
);
?>
Modifying Array Values
 Modifying an array value is as simple as modifying any other variable value: simply assign a new
value to the element using either its index or its key.
 Consider the following example, which modifies the second element of the $meats array to hold

DEPARTMENT OF BCA, METTALA Page 5


the value'turkey'instead of 'ham':
Example:
<?php
//definearray
$meats= array(
'fish',
'chicken',
'ham',
'lamb'
);
//change'ham'to'turkey'
$meats[2]= 'turkey';
?>

 To remove an element from an array, use the unset()function on the corresponding key or
index:
Example:
<?php
//define array
$meats= array(
'fish',
'chicken',
'ham',
'lamb'
);
//remove'fish'
unset($meats[0]);
?>
 You can also remove an element from an array using the array pop()or array
push()function;
Retrieving Array Size
 An important task when using arrays, especially in combination with loops, is finding out how
many values the array contains.
 This is easily accomplished with PHP’s count() function, which accepts the array variable
as a parameter and returns an integer value indicating how many elements it contains.

DEPARTMENT OF BCA, METTALA Page 6


example:
<?php
//definearray
$data= array('Monday','Tuesday', 'Wednesday');
//getarraysize
echo'Thearray has'.count($data).'elements';
?>
Nesting Arrays
 PHP also allows you to combine arrays, by placing one inside another to an unlimited depth.
 This can come in handy when dealing with structured, hierarchically arranged information.
example:
<?php
//define nested array
$phonebook= array(
array(
'name'=>'Raymond Rabbit',
'tel'=>'1234567',
'email'=>'ray@[Link]',
), array(
'name'=>'DavidDuck',
'tel'=>'8562904',
'email'=>'dduck@[Link]',
), array(
'name'=>'HaroldHorse',
'tel'=>'5942033',
'email'=>'kingharold@[Link]',
)
);
?>
PROCESSING ARRAYS WITH LOOPS AND ITERATORS
 Your PHP program will need to work its way through an array, performing an operation or
calculation on each value it finds.
 The best way to do this is with a loop, which sets up an array and then iterates over it
using for loop.
For loop:

DEPARTMENT OF BCA, METTALA Page 7


<?php
//definearray
$cities=
array('London','Paris','Madrid','LosAngeles','Bombay','Jakarta');
//iterateoverarray
//printeachvalue
for($i=0;$i<count($cities);$i++){
echo$cities[$i]."\r\n";
}
?>
The for each loop statement
The for each statement issued to loop through arrays.
For each pass the value of the current array element is assigned to $value and the array pointer is
moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
for each( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2

DEPARTMENT OF BCA, METTALA Page 8


Value is 3
Value is 4
Value is 5
The Array Iterator
 An Array Iterator, which provides a ready-made, extensible tool to loop over array elements.
Here’s a simple example:
Example:
<?php
//definearray
$cities= array(
"United Kingdom"=>"London",
"United States" =>"Washington",
"France"=>"Paris",
"India"=>"Delhi"
);

//createanArrayIteratorobject
$iterator= newArrayIterator($cities);
//rewindtobeginningofarray
$iterator->rewind();
//iterate overarray
//print eachvalue
while($iterator>valid())
{
print$iterator->current(). "isin". $iterator->key().". \r\n";
$iterator->next();
}
?>
 In this listing, an Array Iterator object is initialized with an array variable, and the object’s
rewind()method is used to reset the internal array pointer to the first element of the
[Link],

USING ARRAYS WITH FORMS


 Arrays are particularly potent when used in combination with form elements that support more than
one value, such as multiple-selection list boxes or grouped checkboxes.
 To capture a user’s input in an array, simply add square braces to the form element’s 'name' to
DEPARTMENT OF BCA, METTALA Page 9
automatically convert it into a PHP array when the form is submitted.
Example:
<htmlxmlns="[Link] lang="en">
<head>
<title>Project 4-2:PizzaToppingSelector</title>
</head>
<body>
<h2>Project4-2: PizzaToppingSelector</h2>
<formmethod="post" action="[Link]">
Select yourfavouritepizzatoppings: <br/>
<input type="checkbox"name="toppings[]" value="tomato">Tomato</input>
<input type="checkbox"name="toppings[]" value="onion">Onion</input>
<input type="checkbox"name="toppings[]"value="jalapenos">Jalapeno
peppers</input>
<input type="checkbox"name="toppings[]"value="olives">Olives</input>
<input type="checkbox"name="toppings[]" value="mint">Mint</input>
<input type="checkbox"name="toppings[]"value="pineapple">Pineapple</input>
<input type="checkbox"name="toppings[]" value="bacon">Bacon</input>
<input type="checkbox"name="toppings[]" value="chicken">Chicken</input>
<input type="checkbox"name="toppings[]" value="ham">Ham</input>
<input type="checkbox"name="toppings[]"
value="anchovies">Anchovies</input>
<input type="checkbox"name="toppings[]"value="x-
cheese">Extracheese</input>
<p>
<input type="submit" name="submit"value="Submit"/>
</form>
</body>
</html>

And here’s the code for the form submission script ([Link]):

<!DOCTYPEhtmlPUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN"


"DTD/[Link]">
<htmlxmlns="[Link] lang="en">

DEPARTMENT OF BCA, METTALA Page 10


<head>
<title>Project 4-2:PizzaToppingSelector</title>
</head>
<body>
<h2>Project4-2: PizzaToppingSelector</h2>You selected the following
toppings: <br/>
<ul>
<?php
For each($_POST['toppings'] as$t) {
echo"<li>$t</li>\r\n";
}
?>
</ul>
</body>
</html>

A Web form to select pizza toppings


 When the Web form is submitted, PHP automatically places all the checked values into the
$_POST['toppings']array.
 This array can then be processed like any other array—in this case, with a foreach loop that prints
the selected toppings in an ordered list.

DEPARTMENT OF BCA, METTALA Page 11


The result of submitting the form

WORKINGWITHARRAYFUNCTIONS
 PHP has numerous built-in array manipulation functions, supporting operations ranging from array
search and comparison to sorting and conversion operations.
Converting Between Strings and Arrays
 PHP lets you convert a string into an array, by splitting the string on a user-defined separator and
assigning there suiting segments to an array. The Common PHP Array Functions are,

Function WhatItDoes
explode() Splitsastringintoarray elements
implode() Joinsarray elementsintoastring
range() Generates anumberrange asanarray
min() Findsthesmallestvalueinanarray
max() Findsthelargestvalueinanarray
shuffle() Randomlyrearrangesthesequenceofelementsinanarray
array_slice() Extractsasegmentofanarray
array_shift() Removesanelementfromthebeginningofanarray
array_unshift() Addsanelementtothebeginningofanarray
array_pop() Removesanelementfromtheendofanarray
array_push() Addsanelementtotheendofanarray
array_unique() Removesduplicateelementsfromanarray
array_reverse() Reverses thesequenceofelementsinanarray
array_merge() Combinestwoormorearrays
array_intersect( Calculatesthecommonelementsbetweentwoormorearrays
array_diff()
) Calculatesthedifferencebetweentwoarrays
in_array() Checksifaparticularvalueexistsinanarray
array_key_exist Checksifaparticularkeyexistsinanarray
sort()
s() Sortsanarray
asort() Sortsanassociativearray byvalue
ksort() Sortsanassociativearray bykey
rsort() Reverse-sortsanarray
krsort() Reverse-sortsanassociativearray byvalue
DEPARTMENT OF BCA, METTALA Page 12
arsort() Reverse-sortsanassociativearray bykey

 The properly named explode() function, which accepts two arguments—these parameter
and the source string—and returns an array.
example:
<?php
//definestring
$str= 'tinker,tailor,soldier,spy';
//convertstring toarray
//output:('tinker','tailor','soldier,'spy')
$arr= explode(',',$str);
print_r($arr);
?>

 It’s also possible to reverse the process, joining the elements of an array into a single
string using user-supplied “glue.”The PHP function for this is named implode(), and
it’s illustrated in the next listing:
Example:
<?php
//definearray
$arr= array('one','two','three','four');
//convertarraytostring
//output: 'one andtwo andthree andfour'
$str= implode(' and',$arr);
print_r($str);
?>

Extracting Array Segments


 PHP allows you to slice an array into smaller parts with the array_slice()function, which
accepts three arguments: the original array, the index position (offset) at which to start slicing,
and the number of elements to return from the starting offset .The following listing illustrates
this in action:
Example:
<?php
//definearray

DEPARTMENT OF BCA, METTALA Page 13


$rainbow=
array('violet','indigo','blue','green','yellow','orange','red');
//extract3 centralvalues
//output:('blue', 'green','yellow')
$arr= array_slice($rainbow,2,3);
print_r($arr);
?>
AddingandRemovingArrayElements
 PHP comes with four functions that allow you to add or remove elements from the beginning or
end of an array:
 The array_unshift()function adds an element to the beginning of an array; the
array_shift()function removes the first element of an array;
 Thearray_push()function adds an element to the end of an array; and the
array_pop()function removes the last element of an array.
Example:
<?php
//definearray
$movies= array('The LionKing', 'Cars','ABug\'s Life');
//removeelement frombeginningofarray
array_shift($movies);
//removeelement fromendofarray
array_pop($movies);
//addelementtoendofarray
array_push($movies,'Ratatouille');
//addelementtobeginningofarray
array_unshift($movies, 'TheIncredibles');

//printarray
//output:('TheIncredibles','Cars','Ratatouille')
print_r($movies);
?>
Removing Duplicate Array Elements
 PHPlets you strip an array of duplicate values with its array_unique()function, which
accepts an array and returns a new array containing only unique [Link] next listing
illustrates it in action:
Example:
DEPARTMENT OF BCA, METTALA Page 14
<?php
//definearray
$duplicates= array('a','b','a','c','e','d','e');
//removeduplicates
//output:('a','b','c','e','d')
$uniques= array_unique($duplicates);
print_r($uniques);
?>
Searching Arrays
The in_array()function looks through an array for a specified value and returns true if found.
Example:
<?php
//definearray
$cities= array('London','Paris','Barcelona','Lisbon','Zurich');
//searcharrayforvalue
echoin_array('Barcelona', $cities);
?>
Sorting Arrays
 PHPcomes with a number of built-in functions designed for sorting array elements in different
ways.
 The first of these is the sort()function, which lets you sort numerically indexed arrays
alphabetically or numerically, from lowest to highest value.
example:
<?php
//definearray
$data= array(15,81,14,74,2);
//sort andprint array
//output:(2,14,15,74,81)
sort($data); print_r($data);
?>
Merging Arrays
PHPlets you merge one array into another with its array_merge()function, which accepts one or
more array [Link] following listing and output illustrates its use:
Example:
<?php

DEPARTMENT OF BCA, METTALA Page 15


//definearrays
$dark= array('black', 'brown','blue');
$light= array('white','silver','yellow');
//mergearrays
//output:('black', 'brown','blue','white','silver','yellow')
$colors= array_merge($dark,$light);
print_r($colors);
?>

WORKING WITH DATES AND TIMES


 It nevertheless allows programmers a great deal of flexibility when creating, formatting, and
manipulating such values.
Generating Dates and Times
 Generating a timestamp is usually accomplished with the mktime() function, which accepts a
series of date and time parameters and converts them into a timestamp.
Example:
<?php
//return timestamp for Jan5 200810:15
//output: 1199508300
echomktime(10,15,00,1,5,2008);
?>
 Another way to get the current date and time is with PHP’s getdate()function, which returns an
associative array containing information about the current date and time.
Example:
<?php
//getcurrentdateandtimeasarray
$now = getdate();
//output:'Itisnow 19:26:23on 12-11-2007'
echo'Itisnow '.$now['hours'].':'.$now['minutes'].':'
. $now['seconds'].'on'.$now['mday'].'-'.$now['mon'].'-'
. $now ['year'];
?>
Formatting Dates and Times
 This function accepts two arguments: a formatting string and a timestamp.
 The formatting string is a sequence of characters, each of which has a special meaning; it’s possible
to format a UNIX timestamp with date()to customize the display of a date/time value.
DEPARTMENT OF BCA, METTALA Page 16
Example:
<?php
//output:"Itisnow 12:28pm 20 Mar 2008"
echo'Itisnow '.date("h:iad M Y",mktime(12,28,13,3,20,2008));
There are some FormattingCodesforthedate()Function
Character WhatItMeans
D Dayofthemonth(numeric)
D Dayoftheweek(string)
L Dayoftheweek(string)
F Month(string)
M Month(string)
M Month(numeric)
Y Year
H Hour(in12-hour format)
H Hour(in24-hour format)
A AMorPM
I Minute
S Second

Useful Date and Time Functions


 PHPalsosupportsmanyotherdate/timemanipulationfunctions,whichallowyoutocheckif a date is valid
or convert between time zones. CommonPHPDateFunctions are,
Function WhatItDoes
checkdate() Checksadateforvalidity
strtotime() CreatestimestampsfromEnglish-language descriptions
gmdate() ExpressesatimestampinGMT

Checking Date Validity


 Auseful built-in function is the checkdate()function, which accepts a month, day,and year
combination and returns a true/false value indicating whether the corresponding date is valid.
 Consider the following example, which illustrates it by testing the date30 February 2008:
Example:
<?php
//output:'Dateisinvalid'
if(checkdate(2,30,2008)) {
echo'Date isvalid';
} else{
echo'Date isinvalid';
}

DEPARTMENT OF BCA, METTALA Page 17


?>
Calculating GMT Time
 PHP’s gmdate()function works exactly like its date()function, except that it
returnsGMTrepresentations of formatted date strings, instead of local time representations.
Example:
<?php
//returnsGMT timerelative to'now'
echogmdate('H:i:sd-M-Y',mktime());
//returnsGMT timerelative to'00:011-Dec-2007'
//output: '18:31:00 30-Nov-2007'
echogmdate('H:i:sd-M-Y',mktime(0,1,0,12,1,2007));
?>
**************************** UNIT III COMPLETED*******************************
QUESTION BANK
UNIT III
2 MARKS
1. List the types of array.
2. What is numeric array?
3. What is an associative array?
4. Define multidimensional array.
5. How will you store a data in array?
6. How will you assign array values?
7. How to modify an array?
8. Define nesting array.
9. Define array iterator.
10. Write some php array functions.
11. What is implode and explode functions?
12. How will you add and remove array elements?
13. What is the use of in_array() functions?
14. What is sort() function?
15. What is the use of array_merge() function?
16. What is the mktime() function?
17. What is the use of checkdate()?

5 MARKS AND 10 MARKS


1. Explain the topic of date and time functions.
2. Write the procedure to work with arrays.
3. How will you use forms in arrays?
4. How to process arrays with loops and iterations?
5. How will you store a data in array? And explain it.
6. Write the procedure to work with an array.

DEPARTMENT OF BCA, METTALA Page 18


UNIT IV

CHAPTER I

USING FUNCTIONS AND CLASSES

PHP USER DEFINED FUNCTION

 In all programming and scripting language, a function is a block of statements that can be used
repeatedly in a program. In PHP, the concept of the function is the same as in other language like
'C'.
 There are more than 1,000 in-built functions into the standard PHP distribution. Besides these we can
define functions as per our requirements. These are called 'User Defined Function'.
SYNTAX:

Function function-name ()
{
statement 1 :
statement 2 :
statement 3 :
......
}

Elements of function
 Function: A function declaration starts with the special word 'function'.
 Name of the function: The function name is defined by the user.A valid function name starts with a
letter or underscore, followed by any number of letters, numbers, or under [Link] that
function names are case-insensitive.
 Opening and Closing curly braces ({ } ): The function body enclosed within a pair of braces which
may contain variable names and actual function code. The opening curly brace ( { ) indicates the
beginning of the function code and the closing curly ( } ) brace indicates the termination of the
function.
Example:
<?php
function myfunction()

DEPARTMENT OF BCA, METTALA Page 1


{
echo "Good Morning";
}
myfunction();
?>
Example:Functionswith in a function
<?php
function function1()
{
function function2()
{
echo "Good Morning <br>";
}
}
function1();
function2();
?>
PHP Function arguments, Returning Values
 PHP Function arguments
 In PHP information are passed to functions through argument list, which is a comma-
delimited list of expression.
 There are three different ways of passing arguments to a function, arguments by value (the
default), passing by reference, and default argument values.
 PHP Function arguments by values
 The argument can be any valid expression. The expression is evaluated and its value assigned
to the appropriate variable in the function. In the following function $a assigned the value 10
and $b assigned the value 20:
EXAMPLE:
Functionadd($a, $b)
{
...
}
add(10, 20);

 Passing arguments By Refernce

DEPARTMENT OF BCA, METTALA Page 2


 By default the function arguments are passed by value. If you want to allow a function to
change its arguments, you must pass the arguments by reference.
 To pass an argument to a function as reference, simply add an ampersand (&) character
before the variable name.
EXAMPLE:
<?php
function cube(&$x)
{
$x = $x * $x * $x;
}
$result = 5;
cube($result);
echo $result;
?>
OUTPUT
125
 Default Argument Value
 In the following example the function wage() use a default parameter.
 When we have called the function without arguments it takes the default value as argument.
EXAMPLE:
<?php
function wage($minwage= 100)
{
echo "The wage is : $minwage <br />" ;
}<
wage(200);
wage();
wage(100);
?>
OUTPUT
The wage is : 200
The wage is : 100
The wage is : 100

 Php Returning Values

DEPARTMENT OF BCA, METTALA Page 3


 In PHP values are returned by return statement. The return values must be specified in the
variable.
 If the statement is called within a function the function is terminated immediately and pass
control back to previous position from which it was [Link] return statement can return
any type of data.
EXAMPLE:
 In the following example a function accept a number and calculate the cube of that number
using return statement.
<?php
function cube($x)
{
return $x * $x * $x;
}
echo "The cube of 4 is : ".cube(4)."<br />";
echo "The cube of 9 is : ".cube(9)."<br />";
echo "The cube of 20 is : ".cube(20)."<br />";
?>
Output
The cube of 4 is : 64
The cube of 9 is : 729
The cube of 20 is : 8000

OBJECT ORIENTED PROGRAMMING IN PHP


Object Oriented Concepts:
Before we go in detail, lets define important terms related to Object Oriented Programming.
 Class: This is a programmer-defined data type, which includes local functions as well as local data.
You can think of a class as a template for making many instances of the same kind (or class) of
object.
 Object: An individual instance of the data structure defined by a class. You define a class once and
then make many objects that belong to it. Objects are also known as instance.
 Member Variable: These are the variables defined inside a class. This data will be invisible to the
outside of the class and can be accessed via member functions. These variables are called attribute of
the object once an object is created.
 Member function: These are the function defined inside a class and are used to access object data.

DEPARTMENT OF BCA, METTALA Page 4


 Inheritance: When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.
 Parent class: A class that is inherited from by another class. This is also called a base class or super
class.
 Child Class: A class that inherits from another class. This is also called a subclass or derived class.
 Polymorphism: This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it make take different number of
arguments and can do different task.
 Overloading: a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly functions can also be
overloaded with different implementation.
 Data Abstraction: Any representation of data in which the implementation details are hidden
(abstracted).
 Encapsulation: refers to a concept where we encapsulate all the data and member functions together
to form an object.
 Constructor: refers to a special type of function which will be called automatically whenever there
is an object formation from a class.
 Destructors: refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
Defining PHP Classes:
The general form for defining a new class in PHP is as follows:

<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>

Here is the description of each line:


 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function definitions.

DEPARTMENT OF BCA, METTALA Page 5


 Variable declarations start with the special form var, which is followed by a conventional $ variable
name; they may also have an initial assignment to a constant value.
 Function definitions look much like standalone PHP functions but are local to the class and will be
used to set and access object data.
Example:
Here is an example which defines a class of Books type:

<?php
class Books{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>

The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
 Once you defined your class, then you can create as many objects as you like of that class type.
Following is an example of how to create object using new operator.

$physics = new Books;


$maths = new Books;
$chemistry = new Books;

DEPARTMENT OF BCA, METTALA Page 6


 Here we have created three objects and these objects are independent of each other and they
will have their existence separately.
 Next we will see how to access member function and process member variables.

The relationship between classes and objects

Calling Member Functions


 After creating your objects, you will be able to call member functions related to that object.
 One member function will be able to process member variable of related object [Link]
example shows how to set title and prices for the three books by calling member functions.

$physics->setTitle( "Physics for High School" );


$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example:

$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce following result:

DEPARTMENT OF BCA, METTALA Page 7


Physics for High School
Advanced Chemistry
Algebra
10
15
7

Constructor Functions:
 Constructor Functions are special type of functions which are called automatically whenever an
object is created.
 So we take full advantage of this behavior, by initializing many things through constructor functions.
 PHP provides a special function called __construct() to define a constructor. You can pass as many
as arguments you like into the constructor function.
 Following example will create one constructor for Books class and it will initialize price and title for
the book at the time of object creation.

function __construct( $par1, $par2 ){


$this->price = $par1;
$this->title = $par2;
}

 Now we don't need to call set function separately to set price and title. We can initialize these two
member variables at the time of object creation only. Check following example below:

$physics = new Books( "Physics for High School", 10 );


$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */


$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce following result:

DEPARTMENT OF BCA, METTALA Page 8


Physics for High School
Advanced Chemistry
Algebra
10
15
7

Destructor:
 Like a constructor function you can define a destructor function using function __destruct ().
 You can release all the resources with-in a destructor.
Inheritance:
 PHP class definitions can optionally inherit from a parent class definition by using the extends
clause. The syntax is as follows:

class Child extends Parent {


<definition body>
}

The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics:
 Automatically have all the member variable declarations of the parent class.
 Automatically has all the same a member function as the parent, which (by default) will work the
same way as those functions do in the parent.
 Following examples inherit Books class and adds more functionality based on the requirement.

class Novel extends Books{


var publisher;
function setPublisher($par){
$this->publisher = $par;
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}

 Now apart from inherited functions, class Novel keeps two additional member functions.
Function Overriding:
 Function definitions in child classes override definitions with the same name in parent classes.
 In a child class, we can modify the definition of a function inherited from parent class.

DEPARTMENT OF BCA, METTALA Page 9


 In the following example getPrice and getTitle functions are overridden to return some values.

function getPrice(){
echo $this->price . "<br/>";
return $this->price;
}
function getTitle(){
echo $this->title . "<br/>";
return $this->title;
}

Public Members:
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be
accessed in three possible situations:
 From outside the class in which it is declared
 From within the class in which it is declared
 From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members
of a class then you define class members as private or protected.

Private members:
 By designating a member private, you limit its accessibility to the class in which it is declared.
 The private member cannot be referred to from classes that inherit the class in which it is declared
and cannot be accessed from outside the class.
 A class member can be made private by using private keyword in front of the member.

class MyClass {
private $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");

DEPARTMENT OF BCA, METTALA Page 10


}
private function myPrivateFunction() {
return("I'm not visible outside!");
}
}

 When MyClass class is inherited by another class using extends, myPublicFunction() will be visible,
as will $driver.
 The extending class will not have any awareness of or access to myPrivateFunction and $car,
because they are declared private.
Protected members:
 A protected property or method is accessible in the class in which it is declared, as well as in classes
that extend that class.
 Protected members are not available outside of those two kinds of classes. A class member can be
made protected by using protected keyword infront of the [Link] is different version of
MyClass:

class MyClass {
protected $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
protected function myPrivateFunction() {
return("I'm visible in child class!");
}
}

Interfaces:
 Interfaces are defined to provide a common function names to the implementers.

DEPARTMENT OF BCA, METTALA Page 11


 Different implementers can implement those interfaces according to their requirements. You can say,
interfaces are skeltons which are implemented by [Link] of PHP5, it is possible to define an
interface, like this:

interface Mail {
public function sendMail();
}

 Then, if another class implemented that interface, like this:

class Report implements Mail {


// sendMail() Definition goes here
}

Constants:
 A constant is somewhat like a variable, in that it holds a value, but is really more like a function
because a constant is immutable.
 Once you declare a constant, it does not [Link] one constant is easy, as is done in this
version of MyClass:

class MyClass {
constrequiredMargin = 1.7;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}

 In this class, required Margin is a constant.


 It is declared with the keyword const, and under no circumstances can it be changed to anything
other than 1.7. Note that the constant's name does not have a leading $, as variable names do.
Abstract Classes:
 An abstract class is one that cannot be instantiated, only inherited.
 You declare an abstract class with the keyword abstract, like this: When inheriting from an abstract
class, all methods marked abstract in the parent's class declaration must be defined by the child;
additionally, these methods must be defined with the same visibility.

abstract class MyAbstractClass {


abstract function myAbstractFunction() {

DEPARTMENT OF BCA, METTALA Page 12


}
}

 Note that function definitions inside an abstract class must also be preceded by the keyword abstract.
It is not legal to have abstract function definitions inside a non-abstract class.
Static Keyword:
 Declaring class members or methods as static makes them accessible without needing an
instantiation of the class.
 A member declared as static can not be accessed with an instantiated class object (though a static
method can).Try out following example:

<?php
class Foo
{
public static $my_static = 'foo';

public function staticValue() {


return self::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";

Final Keyword:
 PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
 Following example results in Fatal error: Cannot override final method Base Class::more Testing()

<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called<br>";
}

DEPARTMENT OF BCA, METTALA Page 13


}

class ChildClass extends BaseClass {


public function moreTesting() {
echo "ChildClass::moreTesting() called<br>";
}
}
?>

Calling parent constructors:


 Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's
constructor explicitly and then doing whatever is necessary in addition for instantiation of the
subclass. Here's a simple example:

class Name
{
var $_firstName;
var $_lastName;
function Name($first_name, $last_name)
{
$this->_firstName = $first_name;
$this->_lastName = $last_name;
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name
{
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name) {
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString() {
return(Name::toString() . " " . $this->_middleInitial);

DEPARTMENT OF BCA, METTALA Page 14


}
}

CHAPTER II

WORKINGWITHFILES AND DIRECTORIES


READINGFILES
PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into an array, from
the local file system or a remote URL, by lines, bytes, or characters.

Reading Local Files


The easiest way to read the contents of a disk file in PHPis with the file_get_ contents()function.
This function accepts the name and path to a disk file, and reads the entire file into a string variable in one
fell swoop.

Example:
<?php
//readfile intostring
$str= file_get_contents('[Link]') ordie('ERROR:Cannotfind
file');
echo$str;
?>
 An alternative method of reading data from a file is PHP’s file()function, which accepts the name
and path to a file and reads the entire file into an array, with each element of the array representing
one line of the file.
 To process the file, all you need do is iterate over the array using a foreachloop.
Example:
<?php
//readfile intoarray
$arr= file('[Link]') ordie('ERROR:Cannotfind
file');
foreach($arras$line) {
echo$line;
}
?>

DEPARTMENT OF BCA, METTALA Page 15


Reading Remote Files
Both file_get_contents()and file()also support reading data from URLs, using either the HTTP or
FTP protocol, which reads an HTML file off the Web into an array:

Example:
<?php
//readfile intoarray
$arr= file('[Link]
foreach($arras$line) {
echo$line;
}
?>
 In case of slow network links, it’s sometimes more efficient to read a remote file in “chunks,” to
maximize the efficiency of available network bandwidth.
 To do this, use the fgets()function to read a specific number of bytes from a file, as in the next
example:
<?php
//readfile intoarray(chunks)
$str= '';$fp= fopen('[Link]
die('ERROR: Cannot openfile');
while(!feof($fp)) {
$str.=fgets($fp,512);
} fclose($fp);
echo$str;
?>
 First, the fopen()function: it accepts the name of the source file and an argument indicating
whether the file is to be opened in read ('r'), write ('w'), or append ('a') mode,and then creates a
pointer to the file.
 Next, a while loop calls the fgets()function continuously in a loop to read a specific number of
bytes from the file and append these bytes to a string variable; this loop continues until the
feof()function returns true, indicating that the end of the file has been reached.
 Once the loop has completed, the fclose()function destroys the file pointer.

WRITING FILES

DEPARTMENT OF BCA, METTALA Page 16


 The flip side of reading data from files is writing data to them. And PHP comes with a couple of
different ways to do this as well.
 The first is the file_put_contents() function, a close cousin of the
file_get_contents()function you read about in the preceding section: this function accepts a filename
and path, together with the data to be written to the file,

Example:

<?php
//writestringtofile
$data= "A fish \noutof\n water\n";
file_put_contents('[Link]', $data)or die('ERROR:Cannotwritefile');
echo'Datawritten tofile';
?>
Writing a file
 A new file can be written or text can be appended to an existing file using the PHP fwrite() function.
 This function requires two arguments specifying a file pointer and the string of data that is to be
written. Optionally a third integer argument can be included to specify the length of the data to write.
 If the third argument is included, writing would will stop after the specified length has been reached.
 The following example creates a new text file then writes a short text heading in site it. After
closingthisfileitsexistenceisconfirmedusingfile_exist()functionwhichtakesfilenameas an argument
Example:
<?php
$filename = "/home/user/guest/[Link]";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This isa simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>

DEPARTMENT OF BCA, METTALA Page 17


</head>
<body>
<?php
if(file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
PROCESSING DIRECTORIES
 PHP also allows developers to work with directories on the file system, iterating through directory
contents or moving forward and backward through directory trees.
 Iterating through a directory is a simple matter of calling PHP’s Directory Iterator object,

EXAMPLE

 Directory manipulation functions . . . as in the following listing:


<?php
//createdirectorypointer
$dp= opendir('.') ordie('ERROR:Cannot open directory');
//readdirectory contents
//print filenamesfound
while($file = readdir($dp)) {
if ($file!='.'&&$file !='..'){
echo"$file\n";
}
}
//destroydirectorypointer

DEPARTMENT OF BCA, METTALA Page 18


closedir($dp);
?>
 Here, the opendir()function returns a pointer to the directory named in the function [Link]
pointer is then used by the readdir()function to iterate over the directory, returning a single entry each
time it is invoked.
 It’s then easy to filter out the .and ..directories, and print the names of the remaining entries. Once
done, the closedir() function closes the file pointer.
PHPFile and Directory Functions

Function What It Does


file_exists() Tests if a file or directory exists
filesize() Returns the size of a file in bytes
realpath() Returns the absolute path of a file
pathinfo() Returns an array of information about a file and its path
stat() Provides information on file attributes and permissions
is_readable() Tests if a file is readable
is_writable() Tests if a file is writable
is_executable() Tests if a file is executable
is_dir() Tests if a directory entry is a directory
is_file() Tests if a directory entry is a file
copy() Copies a file
rename() Renames a file
unlink() Deletes a file
mkdir() Creates a new directory
rmdir() Removes a directory
include()/require() Reads an external file into the current PHP script

Checking if a File or Directory Exists


 If you try reading or appending to a file that doesn’t exist, PHP will typically generate a fatal error.
 To avoid these error messages, always check that the file or directory you’re attempting to access
already exists, with PHP’s file_exists()function.

Example:

<?php
//checkfile
if(file_exists('[Link]')){
$str= file_get_contents('[Link]');

DEPARTMENT OF BCA, METTALA Page 19


} else{
echo 'Namedfiledoesnotexist. ';
}

//checkdirectory
if(file_exists('somedir')){
$files= scandir('somedir');
} else{
echo 'Nameddirectory doesnotexist.';
}
?>
Calculating File Size
 To calculate the size of a file in bytes, call the filesize()function with the filename as argument:
Example:
<?php
//getfilesize
//output:'Fileis1327bytes.' if(file_exists('[Link]')){
echo'Fileis'.filesize('[Link]').'bytes.';
} else{
echo 'Namedfiledoesnotexist. ';
}
?>

Finding the Absolute File Path


 To retrieve the absolute file system path to a file, use the real path()function, as in the next
listing:
Example:
<?php
//getfile path
//output:'File path:/usr/local/apache/htdocs/
// /php-book/ch06/listings/[Link]'
if(file_exists('[Link]'))
{
echo'File path:'.realpath('[Link]');
} else
DEPARTMENT OF BCA, METTALA Page 20
{
echo 'Namedfiledoesnotexist. ';
}
?>

 You can also use the pathinfo()function, which returns an array containing the file’s path,
name, and extension. Here’s an example:

<?php
//getfile pathinfoasarray
if(file_exists('[Link]'))
{
print_r(pathinfo('[Link]'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>
Retrieving File Attributes
 You can obtain detailed information on a particular file, including its ownership, permissions,
and modification and access times, with PHP’s stat()function, which returns this information
as an associative array. Here’s an example:

<?php
//getfile information
if(file_exists('[Link]'))
{
print_r(stat('[Link]'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>

 You can check if a file is readable, writable or executable with the is readable (), is

DEPARTMENT OF BCA, METTALA Page 21


writable (), and is executable () functions. The following example illustrates their usage:

<?php
//getfile information
//output:'File is: readablewritable'
if(file_exists('[Link]'))
{
echo'Fileis:';
//checkfor readablebit
if (is_readable('[Link]'))
{
echo'readable';
}
//checkfor writablebit
if (is_writable('[Link]'))
{
echo'writable';
}
//checkfor executablebit
if(is_executable('[Link]'))
{
echo'executable';
}
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>

 The is_dir()function returns true if the argument passed to it is a directory, while the
is_file()function returns true if the argument passed to it is a file. Here’s an example:
<?php
//testiffileordirectory
if(file_exists('[Link]'))
{

DEPARTMENT OF BCA, METTALA Page 22


if(is_file('[Link]'))
{
echo'It\'safile.';
}
if(is_dir('[Link]')){
echo'It\'sadirectory.';
}
} else
{
echo 'ERROR: File doesnotexist.';
}
?>

Creating Directories
 To create a new, empty directory, call the mkdir()function with the path and name of the directory
to be created:
Example:
<?php
if(!file_exists('mydir'))
{
if(mkdir('mydir'))
{
echo'Directory successfully created.';
} else
{
echo 'ERROR: Directory couldnotbecreated.';
}
} else
{
echo 'ERROR: Directoryalreadyexists.';
}
?>
Copying Files
 You can copy a file from one location to another by calling PHP’s copy()function with the file’s
source and destination paths as arguments. Here’s an example:
DEPARTMENT OF BCA, METTALA Page 23
<?php
//copyfile
if(file_exists('[Link]')){
if(copy('[Link]', '[Link]')){
echo'File successfullycopied.';
} else
{
echo 'ERROR: File couldnotbecopied.';
}
} else{
echo 'ERROR: File doesnotexist.';
}
?>
 It’s important to note that if the destination file already exists, the copy()function will overwrite it.

Renaming Files or Directories


 To rename or move a file (or directory), call PHP’s rename()function with the old and new path
names as arguments. Here’s an example that renames a file and a directory, moving the file to a
different location in the process:
Example:
<?php
//rename/movefile
if(file_exists('[Link]'))
{
if(rename('[Link]','../[Link]'))
{
echo'File successfullyrenamed.';
} else
{
echo 'ERROR: File couldnotberenamed.';
}
} else
{
echo 'ERROR: File doesnotexist.';
}

DEPARTMENT OF BCA, METTALA Page 24


//renamedirectory
if(file_exists('mydir'))
{
if(rename('mydir','myotherdir'))
{
echo'Directory successfully renamed.';
} else
{
echo 'ERROR: Directorycouldnotberenamed.';
}
} else
{
echo 'ERROR: Directory doesnotexist.';
}
?>
Reading and Evaluating External Files
 To read and evaluate external files from within your PHPscript, use PHP’s include() or
require()function.
 Avery common application of these functions is to include a standard header, footer, or copyright
notice across all the pages of aWeb site. Here’s an example:

<!DOCTYPEhtmlPUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN"


"DTD/[Link]">
<htmlxmlns="[Link]
<head>
<title>MY WEB PAGE</title>
</head>
<body>
<?phprequire('[Link]');?>
<p/>
Thisis thepagebody.
<p/>
<?phpinclude('[Link]');?>
</body>
</html>

DEPARTMENT OF BCA, METTALA Page 25


QUESTION BANK

UNIT IV

2 MARKS

1. Write short notes on user defined data types in php.


2. What are the elements of function?
3. Define class in php.
4. Define object on php.
5. Define inheritance.
6. What is object overloading?
7. Define data Abstraction.
8. Define encapsulation.
9. How will you create a class in php?
10. How will you create a object in php?
11. How calling member function works?
12. Define construction function.
13. Write short notes on public, protected, private members.
14. What is the use of the file_get_ contents()function?
15. What is the use of fopen(),fget(), fclose() functions?
16. List the php file directory functions.
17. What is the use of file_exist() function?
18. What is the use of file_size() function?
19. What is the use of realpath() function?
20. What is the use of stat() function?
21. What is the use of mkdir() function?
22. What is the use of copy() function?
23. What is the use of remove() function?
24. What is the use of require() and include() function?

5 MARKS AND 10 MARKS

1. Write brief notes on user defined functions in php.


2. Explain about oop concepts in php.
3. How will you read the files from file directory?
4. How will you write the files to file directory?
5. List php directory functions in php and explain it.

DEPARTMENT OF BCA, METTALA Page 26


UNIT V

WORKING WITH DATABASES AND SQL


Features of PHP databases:
 One of the reasons for PHP’s popularity as a Web scripting language is its support for a wide range
of relational database systems.
 This support makes it easy for Web developers to create data-driven Web sites and to prototype new
Web applications quickly and efficiently, with minimal trouble and muss.
 PHP supports more than fifteen different database engines, including Microsoft SQL Server, IBM
DB2, PostgreSQL, MySQL, and Oracle.
 Until PHP5, this support was offered through native database extensions, each with its own
functions and features; however, this made it hard for developers to change from one database
engine to another.
 PHP5 corrected this situation by introducing a common API for database access: the PHP Data
Objects (PDO) extension, which provides a unified interface to working with databases and helps
developers manipulate different databases in a consistent manner.
Introducing Databases and SQL
 In the Internet age, information is no longer represented in filing cupboards instead; it’s stored as
digital ones and zeros in electronic data bases, which are data storage “containers” that impose a
certain structure on information.
 In particular, most electronic data bases today are relational databases, which allow users to
definerelationshipsbetweendifferentdatabasetablesformoreeffectivesearchandanalysis.
 There are a large number of database management systems currently available, some commercial
and some [Link]’ve probably already heard of some of them: Oracle, Microsoft Access, My SQL,
and PostgreSQL.
 These database systems are powerful, feature-rich software applications, capable of organizing and
searching millions of records at very high speeds; as such, they’re widely used by businesses and
government offices, often for mission-critical purposes.
1. Understanding Databases, Records, and Primary Keys:
 Every database is composed of one or more [Link] tables, which structure data into rows and columns,
impose organization on the data

DEPARTMENT OF BCA,METTALA. Page 1


ID Year Location Sales ($)
1 2007 Dallas 9495
2 2007 Chicago 8574
3 2007 Washington 12929
4 2007 New York 13636
5 2007 Los 8748
Angeles
6 2007 Boston 3478
7 2008 Dallas 15249
An example table
Primary key:
 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Primary keys must contain unique values.
 A primary key column cannot contain NULL values.
 Most tables should have a primary key, and each table can have only ONE primary key.
 The primary key of a relational table uniquely identifies each record in the table.
Record:
 A record is a database entry that may contain one or more values. Groups of records are stored in
a table, which defines what types of data each record may contain. Databases may contain multiple
tables which may each contain multiple records.
Database:
 A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view, databases can be classified according to types of content:
bibliographic, full-text, numeric, and images.
2. Understanding Relationships and Foreign Keys
 You already know that a single database can hold multiple tables. In a relational database system,
these tables can be linked to each other by one or more common fields, called foreign keys.
 These foreign keys make it possible to create one-to-one or one-to-many relationships between
different tables, and combine data from multiple tables to create more comprehensive result sets.

DEPARTMENT OF BCA,METTALA. Page 2


Normalization:

 The process of streamlining a database by defining and implementing one-to-one and one-to-many relationships
between its component tables is known as database normalization.

3. Understanding SQL Statements


 Structured Query Language, or SQL, is the standard language used to communicate with a database,
add or change records and user privileges, and perform queries.
 The language, which became an ANSI standard in 1989, is currently used by almost all of today’s
commercial RDBMSs.
SQL statements fall into one of three categories:
 Data Definition Language (DDL) DDL consists of statements that define the structure and
relationships of a database and its tables. Typically, these statements are used to create, delete, and
modify databases and tables; specify field names and types; and set indexes.
 Data Manipulation Language (DML) DML statements are related to altering and extracting
data from a database. These statements are used to add records to, and delete records from, a
database; perform queries; retrieve table records matching one or more user-specified criteria; and
join tables together using their common fields.
 Data Control Language (DCL) DCL statements are used to define access levels and security
privileges for a database. You would use these statements to grant or deny user privileges; assign
roles; change passwords; view permissions; and create rule sets to protect access to data.
 SQL commands resemble spoken English, which makes the language easy to learn. The syntax is
quite intuitive as well: every SQL statement begins with an “action word,” like DELETE,
INSERT,ALTER, or DESCRIBE, and ends with a semicolon.
 Whitespace, tabs, and carriage returns are ignored. Here are a few examples of valid SQL
statements:

CREATEDATABASE library;
SELECT movie FROM movies WHERE rating>4;
DELETEFROM cars WHERE year_of_manufacture<1980;

lists the syntax for some common SQLstatements, with explanations.

DEPARTMENT OF BCA,METTALA. Page 3


USING MY SQL

 In this section, you’ll use the interactive My SQL command-line client to create a database and
tables, add and edit records, and generate result sets matching various criteria.
Create a MySQL Table
 The CREATE TABLE statement is used to create a table in My SQL.
 We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email"
and "reg_date":
Example:
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
After the data type, you can specify other optional attributes for each column:
 NOT NULL - Each row must contain a value for that column, null values are not allowed
 DEFAULT value - Set a default value that is added when no other value is passed
 UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
 AUTO INCREMENT – My SQL automatically increases the value of the field by 1 each time a new
record is added
 PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY
setting is often an ID number, and is often used with AUTO_INCREMENT
Insert Data Into My SQL
 After a database and a table have been created, we can start adding data in them.

DEPARTMENT OF BCA,METTALA. Page 4


 Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
 The INSERT INTO statement is used to add new records to a MySQL table:
Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@[Link]')";
Select Data from a MySQL Database
 The SELECT statement is used to select data from one or more tables
Syntax:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL records from a table:
SELECT * FROM table_name
Example:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
Delete Data From a MySQL Table
 The DELETE statement is used to delete records from a table.
Syntax:
DELETE FROM table_name
WHERE some_column = some_value
Example:
$sql = "DELETE FROM MyGuests WHERE id=3";
Guest Table:
id firstname Lastname email reg_date
1 John Doe john@[Link] 2014-10-22
14:26:15
2 Mary Moe mary@[Link] 2014-10-23
10:22:30
3 Julie Dooley julie@[Link] 2014-10-26
10:48:23

DEPARTMENT OF BCA,METTALA. Page 5


After delete
id firstname lastname email reg_date
1 John Doe john@[Link] 2014-10-22
14:26:15
2 Mary Moe mary@[Link] 2014-10-23
10:22:30

Update Data In a MySQL Table


 The UPDATE statement is used to update existing records in a table,
Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example:
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
MyGuest Table:
id firstname lastname email reg_date
1 John Doe john@[Link] 2014-10-22
14:26:15
2 Mary Moe mary@[Link] 2014-10-23
10:22:30

Getting Data From MySQL Database


 Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. You have several options to fetch data from MySQL.
 The most frequently used option is to use function mysql_fetch_array(). This function returns row
as an associative array, a numeric array, or both. This function returns FALSE if there are no more
rows.
 Below is a simple example to fetch records from employee table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

DEPARTMENT OF BCA,METTALA. Page 6


if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
echo "EMP ID :{$row[0]} <br> ".
"EMP NAME : {$row[1]} <br> ".
"EMP SALARY : {$row[2]} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

ERROR HANDLING
 The default error handling in PHP is very simple. An error message with filename, line number and a
message describing the error is sent to the browser.
PHP Error Handling
 When creating scripts and web applications, error handling is an important part. If your code lacks
error checking code, your program may look very unprofessional and you may be open to security
risks.
Different error handling methods:
 Simple "die()" statements
 Custom errors and error triggers
 Error reporting
[Link] Error Handling: Using the die() function

DEPARTMENT OF BCA,METTALA. Page 7


 The first example shows a simple script that opens a text file:
<?php
$file=fopen("[Link]","r");
?>
 If the file does not exist you might get an error like this:
Warning: fopen([Link]) [[Link]]: failed to open stream:
No such file or directory in C:\webfolder\[Link] on line 2
 To prevent the user from getting an error message like the one above, we test whether the file exist
before we try to access it:
Example:
<?php
if(!file_exists("[Link]")) {
die("File not found");
} else {
$file=fopen("[Link]","r");
}
?>
 Now if the file does not exist you get an error like this:
File not found

[Link] a Custom Error Handler


 Creating a custom error handler is quite simple. We simply create a special function that can be
called when an error occurs in PHP.
 This function must be able to handle a minimum of two parameters (error level and error message)
but can accept up to five parameters (optionally: file, line-number, and the error context):
Syntax:
error_function(error_level,error_message,
error_file,error_line,error_context)

Error Report levels


Parameter Description
error_level Required. Specifies the error report level for the user-defined error. Must be a value
number. See table below for possible error report levels
error_message Required. Specifies the error message for the user-defined error

DEPARTMENT OF BCA,METTALA. Page 8


error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their values, in use when
the error occurred
These error report levels are the different types of error the user-defined error handler can be used
for:
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an
error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the
programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an
E_WARNING set by the programmer using the PHP function
trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the
programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be
caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL
in PHP 5.4)
 Now lets create a function to handle errors:
Function custom Error($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
 The code above is a simple error handling function. When it is triggered, it gets the error level and an
error message.
 It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.
[Link] Error Handler
 The default error handler for PHP is the built in error handler. We are going to make the function
above the default error handler for the duration of the script.

DEPARTMENT OF BCA,METTALA. Page 9


 It is possible to change the error handler to apply for only some errors, that way the script can handle
different errors in different ways.
 However, in this example we are going to use our custom error handler for all errors:
set_error_handler("customError");
 Since we want our custom function to handle all errors, the set_error_handler() only needed one
parameter, a second parameter could be added to specify an error level.
Example
 Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
functioncustomError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}

//set error handler


set_error_handler("customError");

//trigger error
echo($test);
?>
The output of the code above should be something like this:
Error: [8] Undefined variable: test

[Link] an Error
 In a script where users can input data it is useful to trigger errors when an illegal input occurs. In
PHP, this is done by the trigger error () function.

Example
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below");

DEPARTMENT OF BCA,METTALA. Page 10


}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
in C:\webfolder\[Link] on line 6
 An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can
specify what error level is triggered.
Possible error types:
 E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from.
Execution of the script is halted
 E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not
halted
 E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might
be an error, but could also happen when running a script normally
Example
 In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an
E_USER_WARNING occurs we will use our custom error handler and end the script:
<?php
//error handler function
functioncustomError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Ending Script

DEPARTMENT OF BCA,METTALA. Page 11


[Link] Logging
 By default, PHP sends an error log to the server's logging system or a file, depending on how the
error_log configuration is set in the [Link] file.
 By using the error_log() function you can send error logs to a specified file or a remote destination.
 Sending error messages to yourself by e-mail can be a good way of getting notified of specific errors.
[Link] an Error Message by E-Mail
 In the example below we will send an e-mail with an error message and end the script, if a specific
error occurs:
<?php
//error handler function
functioncustomError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@[Link]","From: webmaster@[Link]");
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Webmaster has been notified
 And the mail received from the code above looks like this:
Error: [512] Value must be 1 or below
 This should not be used with all errors. Regular errors should be logged on the server using the
default PHP logging system.
Exceptions Handling:

DEPARTMENT OF BCA,METTALA. Page 12


 PHP 5 has an exception model similar to that of other programming languages. An exception are
important and provides a better control over error handling.
 Three new keyword related to exceptions.
 Try - A function using an exception should be in a "try" block. If the exception does not trigger, the
code will continue as normal. However if the exception triggers, an exception is "thrown".
 Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".
 Catch - - A "catch" block retrieves an exception and creates an object containing the exception
information.
 When an exception is thrown, code following the statement will not be executed, and PHP will
attempt to find the first matching catch block.
 If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ...
 An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try
block.
 Each try must have at least one corresponding catch block. Multiple catch blocks can be used to
catch different classes of exceptions.
 Exceptions can be thrown (or re-thrown) within a catch block.
Example:
Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
try {
$error = 'Always throw this error';
throw new Exception($error);

// Code following an exception is not executed.


echo 'Never executed';

} catch (Exception $e) {


echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

 In the above example $e->getMessage function is uded to get error message.


 There are following functions which can be used from Exception class.

DEPARTMENT OF BCA,METTALA. Page 13


 getMessage()- message of exception
 getCode() - code of exception
 getFile() - source filename
 getLine() - source line
 getTrace() - n array of the backtrace()
 getTraceAsString() - formated string of trace

Creating Custom Exception Handler:


 You can define your own custom exception handler. Use following function to set a user-defined
exception handler function.

string set_exception_handler ( callback $exception_handler )

 Here exception handler is the name of the function to be called when an uncaught exception
occurs. This function must be defined before calling set_exception_handler().
Example:

<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

SQLITE EXTENSION
 SQLite is an in-process library that implements a self-contained, server less, zero-configuration,
transactional SQL database engine.
 It is the one database, which is zero-configured, that means like other database you do not need to
configure it in your system.
 SQLite engine is not a standalone process like other databases, you can link it statically or
dynamically as per your requirement with your application. The SQLite accesses its storage files
directly.
Why SQLite?
 SQLite does not require a separate server process or system to operate.(serverless).
 SQLite comes with zero-configuration, which means no setup or administration needed.

DEPARTMENT OF BCA,METTALA. Page 14


 A complete SQLite database is stored in a single cross-platform disk file.
 SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with
optional features omitted.
 SQLite is self-contained, which means no external dependencies.
 SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
 SQLite supports most of the query language features found in the SQL92 (SQL2) standard.
 SQLite is written in ANSI-C and provides simple and easy-to-use API.
SQLite Commands:
 The standard SQLite commands to interact with relational databases are similar as SQL.
 They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.
 These commands can be classified into groups based on their operational nature:
DDL - Data Definition Language:

Command Description

CREATE Creates a new table, a view of a table, or other object in database

ALTER Modifies an existing database object, such as a table.

Deletes an entire table, a view of a table or other object in the


DROP
database.

DML - Data Manipulation Language:

Command Description

INSERT Creates a record

UPDATE Modifies records

DELETE Deletes records

DQL - Data Query Language:

Command Description

SELECT Retrieves certain records from one or more tables

SQLite Affinity and Type Names:


 Following table lists down various data type names which can be used while creating SQLite3 tables
and corresponding applied affinity also has been shown:

Data Type Affinity

 INT INTEGER

DEPARTMENT OF BCA,METTALA. Page 15


 INTEGER
 TINYINT
 SMALLINT
 MEDIUMINT
 BIGINT
 UNSIGNED BIG INT
 INT2
 INT8

 CHARACTER(20)
 VARCHAR(255)
 VARYING CHARACTER(255)
 NCHAR(55)
TEXT
 NATIVE CHARACTER(70)
 NVARCHAR(100)
 TEXT
 CLOB

 BLOB
NONE
 no datatype specified

 REAL
 DOUBLE
REAL
 DOUBLE PRECISION
 FLOAT

 NUMERIC
 DECIMAL(10,5)
 BOOLEAN NUMERIC
 DATE
 DATETIME

Boolean Datatype:
 SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers
0 (false) and 1 (true).
Date and Time Datatype:

DEPARTMENT OF BCA,METTALA. Page 16


 SQLite does not have a separate storage class for storing dates and/or times, but SQLite is capable of
storing dates and times as TEXT, REAL or INTEGER values.

Storage Class Date Formate

TEXT A date in a format like "YYYY-MM-DD HH:MM:[Link]".

The number of days since noon in Greenwich on November 24,


REAL
4714 B.C.

INTEGER The number of seconds since 1970-01-01 00:00:00 UTC.

SQLite - CREATE Database


 The SQLite sqlite3 command is used to create new SQLite database. You do not need to have any
special privilege to create a database.
Syntax:
 Basic syntax of sqlite3 command is as follows:

$sqlite3 [Link]

Always, database name should be unique within the RDBMS.


Example:
 If you want to create new database <[Link]>, then SQLITE3 statement would be as follows:

$sqlite3 [Link]
SQLite version 3.7.15.22013-01-0911:53:05
Enter".help"for instructions
Enter SQL statements terminated with a ";"
sqlite>

 Above command will create a file [Link] in the current directory.


 This file will be used as database by SQLite engine.
 If you have noticed while creating database, sqlite3 command will provide a sqlite>prompt after
creating database file successfully.
SQLite - INSERT Query
 The SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.
Syntax:
 There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

DEPARTMENT OF BCA,METTALA. Page 17


 Here, column1, column2,...columnN are the names of the columns in the table into which you want
to insert data.
Example:
 Consider you already have created COMPANY table in your [Link] as follows:

sqlite> CREATE TABLE COMPANY(


ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);

SQLite - DROP Table


 The SQLite DROP TABLE statement is used to remove a table definition and all associated data,
indexes, triggers, constraints and permission specifications for that table.
Syntax:
 Basic syntax of DROP TABLE statement is as follows. You can optionally specify database name
along with table name as follows:

DROP TABLE database_name.table_name;

Example:

sqlite>.tables
COMPANY [Link]

 This means COMPANY table is available in the database, so let us drop it as follows:

sqlite>DROP TABLE COMPANY;


sqlite>

SQLite - UPDATE Query


 The SQLite UPDATE Query is used to modify the existing records in a table.
 You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows
would be updated.
Syntax: Following is an example, which would update ADDRESS for a customer whose ID is 6:

sqlite> UPDATE COMPANY SET ADDRESS ='Texas' WHERE ID =6;

Now, COMPANY table would have the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------

DEPARTMENT OF BCA,METTALA. Page 18


1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 Texas 45000.0
7 James 24 Houston 10000.0

 If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not
need to use WHERE clause and UPDATE query would be as follows:

sqlite> UPDATE COMPANY SET ADDRESS ='Texas', SALARY =20000.00;

 Now, COMPANY table will have the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 Texas 20000.0
2 Allen 25 Texas 20000.0
3 Teddy 23 Texas 20000.0
4 Mark 25 Texas 20000.0
5 David 27 Texas 20000.0
6 Kim 22 Texas 20000.0
7 James 24 Texas 20000.0

SQLite - DELETE Query


 The SQLite DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete selected rows, otherwise all the records would be
deleted.
Syntax:
 The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

 You can combine N number of conditions using AND or OR operators.


Example:
 Consider COMPANY table is having the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------

DEPARTMENT OF BCA,METTALA. Page 19


1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0

 Following is an example, which would DELETE a customer whose ID is 7:

sqlite> DELETE FROM COMPANY WHERE ID =7;

 Now COMPANY table will have following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0

 If you want to DELETE all the records from COMPANY table, you do not need to use WHERE
clause with DELETE query, which would be as follows:

sqlite> DELETE FROM COMPANY;

 Now, COMPANY table does not have any record because all the records have been deleted by
DELETE statement.

PDO EXTENSION

 PDO - PHP Data Object.


 An interface for accessing databases in PHP.
 Provides a vendor-neutral lightweight data-access abstraction layer.
 We cannot perform any database functions using the PDO extension by itself; we must use
a database-specific PDO driver to access a database server.
 PDO requires PHP Version 5.1 and available as a PECL extension for PHP 5.0.
 PDO requires the new object oriented features in the core of PHP 5, therefore it will not run with
earlier versions of PHP.

DEPARTMENT OF BCA,METTALA. Page 20


Retrieving Data
PDO works by providing a standard set of functions for common database operations such as connecting,
querying, result set processing and error handling, and internally translating these functions to nativeAPI
calls understood by the database in use.
 consider the following example, which executes a SELECTquery and displays the records
found:
EXMPLE:
<?php
//attempt aconnection try {
$pdo= newPDO('mysql:dbname=music;host=localhost','user','pass');
} catch(PDOException$e)
{
die("ERROR:Could notconnect:". $e->getMessage());
}
//create andexecuteSELECT query
$sql= "SELECT artist_id,artist_nameFROM artists";
if($result= $pdo->query($sql))
{
while($row= $result->fetch())
{
echo$row[0] .":".$row[1]."\n";
}
} else
{
echo"ERROR: Could not execute $sql.". print_r($pdo->errorInfo());
}
//closeconnection
unset($pdo);
?>

using PDO to get data from a database involves steps


The first step is to initialize an instance of the PDO class and pass the object constructor three arguments: a
Data Source Name (DSN) string indicating the type of database to connect to as well as other database-
specific options, a valid database username, and the corresponding password.
list some common DSN string formats.

DEPARTMENT OF BCA,METTALA. Page 21


Database DSNString
MySQL 'mysql:host=host;port=port;dbname=db'
SQLite 'sqlite:path/to/database/file'
PostgreSQ 'pgsql:host=host port=portdbname=dbuser=user
L
Oracle password=pass'
'oci:dbname=//host:port/db'
Firebird 'firebird:User=user;Password=passDatabase=d
b; DataSource=host;Port=port'

 Assuming a successful connection, the next step is to formulate an SQL query and execute it using
PDO’s query () method.
 The return value of this method is a result set, represented by a PDO Statement object.
 The contents of the result set can be processed using the object’s fetch () method, which returns
the next record in the result set as an array (both associative and indexed).
 Individual fields from the record can be accessed as array element s in a loop, using either the field
index or the fieldname.
 The PDO Statement object’s fetch() method accepts an additional modifier, which controls how
result set records are fetched. Some valid values for this modifier are,
Modifier What It Does
PDO::FETCH_NUM Return search record as a numerically indexed array
PDO::FETCH_ASSO Return search record as an associative array keyed on the field
PDO::FETCH_BOTH
C Return
name search record as both a numerically indexed array and
an associative array (default value)
PDO::FETCH_OBJ Return search record as an object with properties
corresponding to the field names
PDO::FETCH_LAZY Return search record as a numerically indexed array, associative
array, and object

WORKING WITH XML


 XML is a markup language that defines set of rules for encoding documents in a format that is both
human-readable and machine-readable.
 So what exactly is a markup language? Markup is information added to a document that enhances its
meaning in certain ways, in that it identifies the parts and how they relate to each other.
 More specifically, a markup language is a set of symbols that can be placed in the text of a document
to demarcate and label the parts of that document.
 following example shows how XML markup looks, when embedded in a piece of text:

DEPARTMENT OF BCA,METTALA. Page 22


<message>
<text>Hello, world!</text>
</message>

 This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>...
</text>. The tags <message> and </message> mark the start and the end of the XML code fragment.
 The tags <text> and </text> surround the text Hello, world!.
XML Technologies
 As XML’s popularity has increased, so too has the list of technologies that use it. Here are a few that
you might have heard about already:
 XML Schema XML Schemas define the structure and format of XML documents, allowing for
more flexible validation and support for data typing, inheritance, grouping, and database linkage.
 XLink :XLink is a specification for linking XMLdata structures together. It allows for more
sophisticated link types than regular HTML hyperlinks, including links with multiple targets.
 XPointer: XPointer is a specification for navigating the hierarchical tree structure of an
XMLdocument, easily finding elements, attributes, and other data structures within the document.
 XSL The Extensible Stylesheet Language (XSL) applies formatting rules to XML documents and
“transforms” them from one format to another.
 XHTML XHTMLcombines the precision of XMLmarkup with the easy-to- understand tags of
HTMLto create a newer, more standards-compliant version of HTML.
 XFormsXForms separates the information gathered in aWeb form from the form’s appearance,
allowing for more stringent validation and easier reuse of forms in different media.
 XML Query XMLQuery allows developers to query XML document and generate result sets, in
much the same way that SQLis used to query and retrieve database records.
 XML Encryption and XML Signature XMLEncryption is a means of encrypting and decrypting
XMLdocuments, and representing the resulting data. It is closely related to XMLSignature, which
provides a way to represent and verify digital signatures with XML.
 SVG ScalableVector Graphics (SVG) uses XMLto describe vector or raster graphical images, with
support for alpha masks, filters, paths, and transformations.
 MathML Math MLuses XML to describe mathematical expressions and formulae, such that they
can be easily rendered by Web browsers.
 SOAP The Simple Object Access Protocol (SOAP) uses XMLto encode requests and responses
between network hosts using HTTP.
Well-Formed and Valid XML
 The XMLspecification makes an important distinction between well-formed and valid
documents.

DEPARTMENT OF BCA,METTALA. Page 23


 A well-formed document follows all the rules for element and attribute names, contains all
essential declarations, contains one (and only one) root element, and follows a correctly nested
element hierarchy below the root element.
 A valid document is one which meets all the conditions of being well-formed and also conforms
to additional rules laid out in a Document Type Definition (DTD) or XML Schema.
XML Parsing Methods
 An XMLdocument is processed by a software application known as an XML parser.
 This parser reads the XML document using one of two approaches, the SimpleAPI for
XML(SAX) approach or the Document Object Model (DOM) approach:
 ASAX parser works by traversing an XML document sequentially, from beginning to end, and
calling specific user-defined functions as it encounters different types of XML constructs.
 ADOM parser, on the other hand, works by reading the entire XML document in one fell
swoop and converting it to a hierarchical “tree” structure in memory. The parser can then be
programmed to traverse the tree, jumping between “sibling” or “child” branches of the tree to
access specific pieces of information.
Simple XML Extension
 PHP has support for both DOM and SAX parsing methods, by far the easiest way to work with XML
data in PHPis via its Simple XML extension.
Working with Elements
 Simple XML represents every XML document as an object and turns the elements within it into a
hierarchical set of objects and object properties.
 Accessing a particular element now becomes as simple as using parent->childnotation to
traverse the object tree until that element is reached.
Example:
considerthefollowingXMLfile([Link]):
<?xmlversion='1.0'?>
<address>
<street>13 HighStreet</street>
<county>Oxfordshire</county>
<city>
<name>Oxford</name>
<zip>OX11BA</zip>
</city>
<country>UK</country>
</address>

DEPARTMENT OF BCA,METTALA. Page 24


 Here’s a PHP script that uses Simple XML to read this file and retrieve the city
name and ZIPcode:
<?php
//loadXML file
$xml =simplexml_load_file('[Link]')
ordie("UnabletoloadXML!");
//accessXML data
//output:'City: Oxford\n Postalcode:OX11BA\n'
echo"City: ". $xml->city->name."\n";
echo"Postal code:". $xml->city->zip."\n";
?>

 To read an XML file with Simple XML, use the simplexml_load_file()function and pass
it the disk path to the target XML file.
 This function will then read and parse the XML file and, assuming it is well-formed, return a
Simple XML object representing the document’s root element.
 This object is only the top level of a hierarchical object tree that mirrors the internal structure of
the XML data: elements below the root element are represented as properties or child objects
and can thus be accessed using the standard parentObject->childObjectnotation.
Working with Attributes
 If an XML element contains attributes, Simple XML has an easy way to get to these as well:
attributes and values are converted into keys and values of a PHP associative array and can be
accessed like regular array elements.
 consider the following example, which reads the [Link] file from the preceding section and
prints each book title found, together with its 'genre'and'rating':
EXAMPLE:
<?php
//loadXML file
$xml =simplexml_load_file('[Link]') ordie("Unableto loadXML!");
//accessXML data
//for eachbook
//retrieve andprint'genre'and'rating'attributes
//output: 'TheShining\nGenre:horror\nRating:5 \n\n...' foreach($xml-
>bookas $book)

DEPARTMENT OF BCA,METTALA. Page 25


{
echo$book->title ."\n";
echo"Genre:". $book['genre']."\n";
echo"Rating: ". $book['rating']. "\n\n";
}
?>
 In this example, a foreachloop iterates over the <book>elements in the XMLdata, turning each
into an object.
 Attributes of the book element are represented as elements of an associative array and can thus be
accessed by key: the key 'genre'returns the value of the 'genre'attribute, and the key
'rating'returns the value of the 'rating' attribute.
Altering Element and Attribute Values
 With SimpleXML, it’s easy to change the content in an XMLfile: simply assign a new value to the
corresponding object property using PHP’s assignment operator (=).
 To illustrate, consider the following PHP script, which changes the title and author of the second
book in [Link] and then outputs the revised XML document:
EXAMPLE:
<?php
//loadXML file
$xml =simplexml_load_file('[Link]') ordie("Unableto
loadXML!");
//changeelementvalues
//setnew titleandauthor for secondbook
$xml->book[1]->title= 'InvisiblePrey';
$xml->book[1]->author= 'JohnSandford';
//outputnew XMLstring
header('Content-Type:text/xml');
echo $xml->asXML();
?>

Using PHP’s DOM Extension


 This extension, which is also enabled by default in PHP5, provides a stylish toolkit that complies
with the DOM Level 3 standard and brings comprehensive XML parsing capabilities to PHP.
Working with Elements
 The DOM parser works by reading an XML document and creating objects to represent the

DEPARTMENT OF BCA,METTALA. Page 26


different parts of that document. Each of these objects comes with specific methods and
properties, which can be used to manipulate and access information about it.
 Thus,the entire XML document is represented as a “tree” of these objects, with the DOM parser
providing a simple API to move between the different branches of the tree.
 To illustrate how this works in practice, let’s revisit the [Link] file from the preceding
section:

<?xml version='1.0'?>
<address>
<street>13 HighStreet</street>
<county>Oxfordshire</county>
<city>
<name>Oxford</name>
<zip>OX11BA</zip>
</city>
<country>UK</country>
</address>

 Here’s a PHP script that uses the DOM extension to parse this file and retrieve the various
components of the address:
<?php
//initializenew DOMDocument
$doc= new DOMDocument();
//disable whitespace-onlytext nodes
$doc->preserveWhiteSpace= false;
//readXML file
$doc->load('[Link]');
//getroot element
$root= $doc->firstChild;
//gettext node'UK'
echo"Country:". $root->childNodes->item(3)->nodeValue."\n";
//gettext node'Oxford'
echo"City: ". $root->childNodes->item(2)->childNodes->
item(0)->nodeValue."\n";
//gettext node'OX1 1BA'

DEPARTMENT OF BCA,METTALA. Page 27


echo"Postal code:". $root->childNodes->item(2)->childNodes->item(1)-
>nodeValue."\n";
//output:'Country:UK \n City: Oxford\n Postal code:OX11BA'
?>
 The first step is always to initialize an instance of the DOM Document object, which represents
an XML document.
 Once this object has been initialized, it can be used to parse an XML file via its load()method,
which accepts the disk path to the target XML file.
 Once the XML document has been load()-ed, it calls the DOM Document object’s
firstChildproperty, which returns a DOM Node object representing the root element
<address>.
 This DOM Node object, in turn, has a childNodesproperty, which returns a collection of all the
child elements of <address>.
 Individual elements of this collection can be accessed via their index position using the
item()method, with indexing starting from zero.
 These elements are again represented as DOM Node objects; as such, their names and values are
therefore accessible via their node Name and node Value properties.
 Thus,theelement<country>,which is the fourth child element under<address>, is accessible via
the path $root->childNodes->item(3),and the text value of this element,'UK',is accessible
via the path $root->childNodes->item(3)->node Value.
 Similarly,the element<name>, which is the first child of the <city>element,is accessible via the
path $root->child Nodes->item(2)->child Nodes->item(0) ,and the text
value'Oxford'is accessible via the path $root->childNodes->item(2)->childNodes-
>item(0)->nodeValue.

DOM relationships
Working with Attributes
 The DOM also includes extensive support for attributes: every DOM Element object comes with a

DEPARTMENT OF BCA,METTALA. Page 28


getAttribute()method, which accepts an attribute name and returns the corresponding value.
example, which prints each book’s rating and genre from [Link]:
<?php
//initializenew DOMDocument
$doc= new DOMDocument();
//disable whitespace-onlytext nodes
$doc->preserveWhiteSpace= false;
//readXML file
$doc->load('[Link]');
//getcollection of<book>elements
//for eachbook
//retrieve andprint'genre'and'rating'attributes
//output: 'TheShining\nGenre:horror\nRating:5 \n\n...'
$books= $doc->getElementsByTagName('book');
foreach($booksas $book){
$title= $book->getElementsByTagName('title')->item(0)->nodeValue;
$rating= $book->getAttribute('rating');
$genre= $book->getAttribute('genre');
echo"$title\n";
echo"Genre:$genre\n";
echo"Rating:$rating\n\n";
}
?>
QUESTION BANK

UNIT V

2 MARKS

1. What are the features of php databases?


2. What is table?
3. What is primary key?
4. What is record?
5. What is database?
6. What is foreign key?
7. Define normalization.
8. What are the categories of SQL statements?
9. Give some examples of SQL statements.
10. How will you create a table in my sql?
11. What are the data type of attributes in my sql?

DEPARTMENT OF BCA,METTALA. Page 29


12. How will you insert in the mysql database?
13. How will you select datas in the mysql database?
14. How will you delete the data’s in the mysql database?
15. How will you update data’s in the sql database?
16. How will you get the data’s from the mysql database?
17. What are the error handling methods in php?
18. How will you create custom error handler?
19. What is the use of set error handler?
20. What is the use of trigger error handler?
21. What is the use of se error handler?
22. What are the possible error types?
23. What are the key words are used as the exception handler in php?
24. What are the exception classes?
25. What is SQLLite?
26. What are the SQLLite commands?
27. How will you create SQLLite database?
28. How will you insert the datas into the SQLLite database?
29. How will you drop the SQLLite table?
30. How will you delete the SQLLite table?
31. What is PDO extension?
32. Define XML?
33. What are the XML Technologies?
34. Define Well formed and valid formed document.
35. What are the XML parsing approaches?

5 MARKS AND 10 MARKS

1. Write notes on databases and sql.


2. What are the steps to access My SQL databases?
3. What are the error handling methods available in php?
4. Explain SQlLite Extension.
5. Discuss about XML and its functions.
6. Explain about DOM Extension.

DEPARTMENT OF BCA,METTALA. Page 30

You might also like