You are on page 1of 40

WEB TECHNOLOGIES

UNIT IV

Syllabus: An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-Form
Validation- Regular Expressions - File handling – Cookies - Connecting to Database.

XML: Basic XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).

Multitier Application Architecture

o Web-based applications are often multitier applications (sometimes referred to as n-tier


applications) that divide functionality into separate tiers (i.e., logical groupings of
functionality).
o Although tiers can be located on the same computer, the tiers of web-based applications often
reside on separate computers.
The below figure presents the basic structure of a three-tier web-based application:

i) The bottom tier (also called the data tier or the information tier) maintains the
application’s data. This tier typically stores data in a relational database management system
(RDBMS).
ii) The middle tier implements business logic, controller logic and presentation
logic to control interactions between the application’s clients and its data.
➢ Business logic in the middle tier enforces business rules and ensures that data is reliable
before the application updates a database or presents data to users.
iii) The top tier, or client tier, is the application’s user interface, which gathers
input and displays output.
Client-side Scripting versus Server-side Scripting

➢ Client-side scripting with JavaScript can be used


o to validate user input,
WT – UNIT IV – R19 Page 1
o to interact with the browser,
o to enhance web pages, and
o to add client/server communication between a browser and a web server.

➢ Limitations of Client-side Scripting


o Browser dependency; the browser or scripting host must support the scripting
language and capabilities.
o Scripts are restricted from arbitrarily accessing the local hardware and file system
for security reasons.
o Another issue is that client-side scripts can be viewed by the client by using the
browser’s source-viewing capability.

➢ Server-side Scripting
o Programmers have more flexibility with server-side scripts, which often
generate custom responses for clients.
o Server-side scripting languages have a wider range of programmatic capabilities
than their client-side equivalents.
o Server-side scripts also have access to server-side software that extends server
functionality.

PHP (Hypertext Preprocessor / Personal Home Page)

o PHP is the most popular server-side scripting language for creating dynamic, data-driven web
applications.

The problem with other Technologies (Servelets and JSP)

JSP PHP
Java Server Pages Hypertext Preprocessor
Server-side programming
Server-side scripting language
technology
Uses Java as the base for Does not need any other
programming programming language
Used to develop small to medium
Used to develop web applications
sized web applications with dynamic
with dynamic content.
content.
JSP requires more code and is PHP is simple and needs fewer lines
complex. of codes.
JSP allows to define custom tags. PHP won't allow custom tags.
JSP has better memory PHP memory management
management techniques techniques are difficult

Requires Access to Java APIs Fewer libraries than JSP

Created by SUN microsystems Created by Rasmus Lerdrof

WT – UNIT IV – R19 Page 2


Running web apps using PHP

Apache, MySQL and PHP Installation

o The Apache HTTP Server, maintained by the Apache Software Foundation, is the most
popular web server in use today because of its stability, efficiency, portability, security and
small size. It’s open source software that runs on Linux, Mac OS X, Windows and numerous
other platforms.

o MySQL is the most popular open-source database management system. It, too, runs on
Linux, Mac OS X and Windows.

o PHP is the most popular server-side scripting language for creating dynamic, data-driven
web applications.

o The Apache HTTP Server, MySQL database server and PHP can each be downloaded and
installed separately, but this also requires additional configuration on our part.

o We’ll use the XAMPP integrated installer provided by the Apache Friends website
(www.apachefriends.org).

What is XAMPP?

XAMPP is the most popular PHP development environment. XAMPP is a completely free, easy to
install Apache distribution containing MariaDB, PHP, and Perl.

XAMPP installation

1. Download the XAMPP software from the link –

http://www.apachefriends.org/en/xampp.html and for 64 bit software go to the below link


https://www.apachefriends.org/download.html

2. Running XAMPP

Once we have installed XAMPP, we can start the Apache and MySQL servers for windows platform
as described below.

Windows:

o Go to c:\xampp folder (or the folder in which we installed XAMPP) and double click
xampp_start.exe.
o If we need to stop the servers, use xampp_stop.exe in the same folder.

3. Testing our Setup of XAMPP

WT – UNIT IV – R19 Page 3


o Once we have started the servers, we can open any web browser on our computer and enter
the address http://localhost:90 to confirm that the web server is up and running
o If it is successful, we will see the page similar to the below one:

The anatomy of a PHP Page


Note:
The basic outline of a PHP script consists of:
1. PHP Opening tag PHP File name ends with .php
2. Comments
3. Statements Example
4. PHP Closing tag
<?php
echo("Hello, World! \n") ;
PHP tag ?>
<?php ?>

o PHP code is inserted between the delimiters <?php and ?> and can be placed anywhere in
HTML.
o PHP tag, informs interpreter to execute PHP code.

Comments
Single line comments: # or //
Multiline comments: /* */

Statements

o In this case the echo() function outputs a quoted string (as its argument) within its
parentheses.
o Each statement must end with a semi-colon (;)

HTML embedded PHP - Example

<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo("Hello, World! \n"); ?>

WT – UNIT IV – R19 Page 4


</body>
</html>

Executing a PHP Script

o Save the file with First_php.php and place this file under C:\xampp\htdocs
o Open browser and launch the URL http://localhost:90/First_php.php

PHP Variables

o All variables are preceded by / Begin with a $


o Followed by name, starting with a letter or _underscore
o Case sensitive
o Don't need to be declared
o PHP variables are loosely typed—they can contain different types of data (e.g., integers,
doubles or strings) at different times
o Initialized at use
o Assigned with a single equals sign =

Assigned by Value
$num = 10 ;
$name= "SVCK" ;

Assigned by Reference
o Prefix & (ampersand) to variable being referenced
$num2 = &$num1 ;

Program on PHP variables


Output
<!DOCTYPE html>
<!-- Simple PHP program. -->
<html>
<?php
$name = "SVCK";
?>
<head>
<meta charset = "utf-8">
<title>Simple PHP document</title>
</head>
<body>
<!-- print variable name’s value -->
<h1><?php print( "Welcome to PHP, $name!" ); ?></h1>
</body>
</html>

PHP Data Types

WT – UNIT IV – R19 Page 5


Converting between Data Types

✓ Converting between different data types may be necessary when performing arithmetic
operations with variables.
✓ Type conversion can be done in two ways:

1. PHP Functions to Convert DataType


2. Type Casting (explicit)

1. PHP Functions to Convert DataType

✓ gettype() and settype()

✓ gettype() - Gives current type of its argument.

✓ settype() - is used to modify the type of each variable.

✓ Function settype takes two arguments—the variable whose type is to


be changed and the variable’s new type.

✓ When converting from a string to a number, PHP uses the value of the number that
appears at the beginning of the string. If no number appears at the beginning, the string
evaluates to 0.

Program on Type Conversion

<!DOCTYPE html>
<html>
<head><title>Type Conversions</title></head>
<body>
<?php
$strvar = "7.3 seconds";
print("<h1>String $strvar as double type : </h1>");
settype($strvar, "double");
print("<h1>$strvar </h1>");
print("<h1>Data type after conversion=".gettype($strvar). "</h1>");
WT – UNIT IV – R19 Page 6
$doublevar = "7.356";
print("<p><h1>Double $doublevar as int type : </h1>");
settype($doublevar, "integer");
print("<h1>$doublevar </h1>");

$intvar = 7;
print("<h1>Int $intvar as String type : </h1>");
settype($intvar, "string");
print("<h1>$intvar </h1>");
?>
</body>
</html>

2. Type Casting

• Another option for conversion between types is casting (or type casting).
• Unlike settype, casting does not change a variable’s content—it creates a temporary copy of
a variable’s value in memory.
• Casting is useful when a different type is required in a specific operation but you would like
to retain the variable’s original value and type.

<html>
<head>
<title>PHP Type Casting</title>
</head>
<body>
<?php
$doublevar = 100.24;
print("<h1>double val=" . $doublevar ."</h1>");
print("<h1>integer value=" . (int)$doublevar ."</h1>");
print("<h1>String value=" . (string)$doublevar ."</h1>");
print("<h1>Type of the data= " . gettype($doublevar) ."</h1>");

?>
</body>
</html>

Output

WT – UNIT IV – R19 Page 7


Keywords

Arithmetic Operators
• PHP provides several arithmetic operators.
• Strings are converted to integers or doubles when they’re used in arithmetic operations.
• A copy of the value of variable str, "3 dollars", is converted to the integer 3 for use in the
calculation.

<!DOCTYPE html>
<html>
<head>
<title>PHP Operators</title>
</head>
<body>
<?php
define("b",30);

$a = 10;
print("<h1> Value of a = $a</h1>");

$a = $a + 10;
print("<h1> Value of a after adding 20 = $a</h1>");

if($a > 20)


print("<h1> Value of a is greater than 20 </h1>");
elseif($a == 20)
print("<h1> Value of a is equal to 20 </h1>");
else
print("<h1> Value of a is less than 20 </h1>");

$a = b + $a;

print("<h1> Value of a = $a </h1>");

?>
</body>

WT – UNIT IV – R19 Page 8


</html>

WT – UNIT IV – R19 Page 9


Strings

• String is a collection of characters.

String Concatenation

• The concatenation operator (.) combines multiple strings in the same print statement.

String Comparison

• Function strcmp() is used to compare two strings.


• The function returns -1 if the first string alphabetically precedes the second string, 0 if the
strings are equal, and1 if the first string alphabetically follows the second.
• Relational operators (==, !=, <, <=, > and >=) can also be used to compare strings.

<html>
<head>
<title>PHP Strings Comparison operations</title>
</head>
<body>
<?php
$sw = array("C","JAVA","Oracle");

if(strcmp($sw[1],"PHP"))
print("<b><p>$sw[1] precedes before PHP</p></b>");

WT – UNIT IV – R19 Page 10


if($sw[1] < "PHP")
print("<b>$sw[1] precedes before PHP</b>");
?>
</body>
</html>

Output

String Processing with Regular Expressions

• Regular Expression is a series of characters that serve as pattern-matching templates (or


search criteria) in strings, text files and databases.
• Function preg_match uses regular expressions to search a string for a specified pattern using
Perl-compatible regular expressions (PCRE).
• Function preg_match takes two arguments—a regular-expression pattern to search for and
the string to search.
• The regular expression must be enclosed in delimiters—typically a forward slash (/) is placed
at the beginning and end of the regular-expression pattern.
• By default, preg_match performs a case-sensitive pattern matches.
• To perform case insensitive pattern matches you simply place the letter i after the regular-
expression pattern’s closing delimiter, as in “/b/i"

Meta characters

• Regular expressions can include meta characters that specify patterns.


• The caret (^) metacharacter matches the beginning of a string
• the dollar sign ($) matches the end of a string
• Bracket expressions are lists of characters enclosed in square brackets ([]) that match any
single character from the list.
• Ranges can be specified by supplying the beginning and the end of the range separated by a
dash (-).
Ex: [a-z] matches any lowercase letter and
[A-Z] matches any uppercase letter.
[a-zA-Z]*ow -> matches any number of letters followed by the literal characters ow

WT – UNIT IV – R19 Page 11


Regular Expression Functions

Program on Regular Expressions

<html>
<head>
<title>PHP-Strings with Regular Expression</title>
</head>
<body>
<?php

$str = "PHP programming";


// Regular Expressions
//search for the word program
if(preg_match("/program/",$str))
print("<b><p> program is found </p></b>");
else
print("<b><p> program is not found </p></b>");

WT – UNIT IV – R19 Page 12


//search for the word PHP
if(preg_match("/^Php/i",$str))
print("<b><p> PHP is found at the beginning</p></b>");
else
print("<b><p> PHP is not found at the beginning</p></b>");

if(preg_match("/[a-z]/",$str))
print("<b><p> a-z is found</p></b>");
else
print("<b><p> a-z is not found</p></b>");

if(preg_match("/[a-z]*ing/",$str))
print("<b><p> ing is found at the end</p></b>");
else
print("<b><p> ing is not found at the end</p></b>");
?>
</body>
</html>

Output

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

• Array names, like other variables, begin with the $ symbol.

There are three different kind of arrays and each array value is accessed using an ID which is
called array index.

• Indexed array − An array with a numeric index. Values are stored and accessed in linear
way.

• Associative array − An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.

• Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices.

PHP Indexed Array


WT – UNIT IV – R19 Page 13
PHP index is represented by number which starts from 0.

We can store number, string and object in the PHP array.

All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

$season=array("summer","winter","spring","autumn");

2nd way:

$season[0]="summer";

$season[1]="winter";

$season[2]="spring";

$season[3]="autumn";

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

PHP Associative Array

• We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

$salary=array(“Sachin"=>"350000",“Jadeja"=>"450000","Kartik"=>"200000");

2nd way:

$salary[" Sachin"]="350000";

$salary[" Jadeja"]="450000";

$salary["Kartik"]="200000";

PHP Multidimensional Array

• PHP multidimensional array is also known as array of arrays.

• It allows you to store tabular data in an array.

• PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.

$emp = array

WT – UNIT IV – R19 Page 14


array(1,“sachin",400000),

array(2,"jadeja",500000),

array(3,“Karthik",300000)

);

Iteration over an array

• PHP provides functions for iterating through the elements of an array


• Each array has a built-in internal pointer, which points to the array element currently being
referenced.
• Function reset sets the internal pointer to the first array element.
• Function key returns the index of the element currently referenced by the internal pointer,
and function next moves the internal pointer to the next element and returns the element.
• To override the automatic numeric indexing performed by function array, you can use
operator =>.
• The value to the left of the operator is the array index and the value to the right is the
element’s value.
• The foreach statement starts with the array to iterate through, followed by the keyword as,
followed by two variables—the first is assigned the index of the element, and the second is
assigned the value of that index

Method 1

<html>
<head>
<title>PHP Arrays</title>
</head>
<body>
<?php

// create array first


print( " <h1><p>Creating the first array</h1></p>" );
$first[ 0 ]="one";
$first[ 1 ] = "two";
$first[ ] = "three";

// print each element’s index and value


for ( $i = 0; $i < count( $first ); ++$i )
print( "<h2>Element $i is $first[$i]</h2>" );
?>
</body>
</html>

Output

WT – UNIT IV – R19 Page 15


b) Method 2

<html>
<head>
<title>PHP Arrays - Method 2</title>
</head>
<body>
<?php

// create array second


print( " <h1><p>Creating the Second array</h1></p>" );

// call function array to create array second


$second = array( "zero", "one", "two", "three" );

// print each element’s index and value


for ( $i = 0; $i < count( $second ); ++$i )
print( "<h2>Element $i is $second[$i]</h2>" );
?>
</body>
</html>

Output

c) Method 3 - Associative Arrays

<html>
<head>
<title>PHP Associative Arrays</title>
</head>
<body>
<?php

WT – UNIT IV – R19 Page 16


// create array third
print( " <h1><p>Creating the third array</h1></p>" );
// assign values to entries using nonnumeric indices
$third[ "sachin" ] = 21;
$third[ "kapil" ] = 25;
$third[ "rahul" ] = 24;
// print each element’s index and value
foreach($third as $element => $value)
print("<h1><p>$element is $value</p></h1>");
?>
</body>
</html>

Output

d) Method 4 - Associative Arrays

<html>
<head>
<title>PHP Associative Arrays - Method 4</title>
</head>
<body>
<?php
// create array months
print( " <h1><p>Function array - Associative Array</h1></p>" );

$months = array("JAN","FEB");

$months = array(
"January" => "JAN", "February" => "FEB");

// print each element’s index and value


foreach($months as $element => $value)
print("<h1><p>$element month is $value</p></h1>");
?>
</body>
</html>

Output

WT – UNIT IV – R19 Page 17


PHP Functions

Function Syntax

function functionName(parameters)
{
function-body
}

Example

<html>
<head>
<title>Function Example</title>
</head>
<body>
<?php
$r = display();
echo "<b><p>$r</p></b>";

function display()
{
echo "<b><p>PHP Function</p></b>";
$i = 10;
return $i;
}
?>
</body>
</html>

Output

list() function

✓ The list() function is used to assign values to a list of variables in one operation.

<!DOCTYPE html>

<html>

<body>

WT – UNIT IV – R19 Page 18


<?php

$colors = array("red","blue","green");

list($red, $blue, $green) = $colors;

echo "I have several colors, a $a, a $b and a $c.";

?>

</body>
</html>
return statement

• The return() statement returns any ensuing value back to the function caller, returning
program control back to the caller’s scope in the process.

Functions can return multiple values

Returning Multiple Values

• With the help of a very useful language construct, list().


• The list() construct offers a convenient means for retrieving values from an array.

<html>
<head>
<title>Functions Return multiple values</title>
</head>
<body>
<?php
function retriveDetails($name,$college)
{
$details[0] = $name;
$details[1] = $college;
return $details;
}
list($n,$c) = retriveDetails("501","SVCK");
echo "<h1>Name = $n - College = $c</h1>";
?>
</body>
</html>

Output

WT – UNIT IV – R19 Page 19


Call-By-Value and Call-By-Reference

• In Pass-By-Value, any changes made to those values within the scope of the function are
ignored outside of the function.
• Passing Arguments by Reference is done by appending an ampersand to the front of the
argument.

<html>
<head>
<title>Call-By-Value and Call-By-Reference Example</title>
</head>
<body>
<?php
//Call by value and call by reference
$x = 10;
$y = 20;
demoParams($x,$y);
echo "<b><p>x = $x</p></b>";
echo "<b><p>y = $y</p></b>";;

// $i is passed by reference and $j is passed by value


function demoParams(&$i,$j)
{
$i = 30;
$j = 40;
$sum = $i + $j;
printf("<b><p>Sum = %d</p></b>",$sum);
}
?>
</body>
</html>

Output

Default Argument Values

• Default values can be assigned to input arguments, which will be automatically assigned to
the argument if no other value is provided.

WT – UNIT IV – R19 Page 20


<html>
<head>
<title>Functions with default values</title>
</head>
<body>

<?php
function sum($i,$j=50)
{
$sum = $i + $j;
return $sum;
}
$x = 10;

$r = sum($x);
echo "<h1>Sum= $r</h1>";
?>

</body>
</html>
Output

Recursive Functions

• Recursive functions, or functions that call themselves, are used to divide an otherwise
complex problem into a simple case, reiterating that case until the problem is resolved.

Program to find out the factorial of a given number using recursion

<html>
<head>
<title>Factorial - Recursion Example</title>
</head>
<body>
<?php
$n=5;
$res = fact($n);
echo "<h1>Factorial of $n is = $res </h1>";

function fact($x)
{
if($x == 0)
return 1;
else
return $x * fact($x-1);

WT – UNIT IV – R19 Page 21


}
?>
</body>
</html>

Output

Function Libraries

• Functions offer a great way to reuse code and are often collectively assembled into libraries
and subsequently repeatedly reused within similar applications.

• PHP libraries are created via the simple aggregation of function definitions in a single file.

<?php

require_once(“Name of PHP program");

?>

user-defined Library Functions

User_Functions.php
<html>
<head>
<title>User defined Library Functions Example
</title>
</head>
<body>
<?php
function add($a,$b)
{
return $a+$b;
}
function sub($a,$b)
{
return $a-$b;
}
?>

Import_Lib_Fun.php

<html>
<head>
<title>Importing Library Functions Example
</title>
</head>
<body>
<?php
WT – UNIT IV – R19 Page 22
require_once("User_functions.php");
$r = add(5,9);
echo "<h1>Sum = $r</h1>";
$r = sub(5,9);

echo "<h1>Sub = $r</h1>";


?>
</body>
</html>

Output:

PHP advanced Concepts

PHP Cookies

What is a Cookie?

▪ A cookie is a piece of information that’s stored by a server in a text file on a client’s


computer to maintain information about the client during and between browsing sessions.

▪ A website can store a cookie on a client’s computer to record user preferences and other
information that the website can retrieve during the client’s subsequent visits.

▪ Websites should not store critical information, such as credit card numbers or passwords, in
cookies, because cookies are typically stored in text files that any program can read.

▪ A server can access only the cookies that it has placed on the client.

▪ A cookie also has an expiration date, after which the web browser deletes it.

Types of Cookies

▪ Session Cookie:

✓ The cookie without an expiration date


✓ It lasts only until the end of the current session—that is, when the user closes the
browser.
▪ Persistent cookie: The cookie with an expiration date

Cookies.php

<html>
<head>
<meta charset = "utf-8">
<title>Writing a cookie to the client computer</title>

WT – UNIT IV – R19 Page 23


<style type = "text/css">
label { width: 7em; float: left; }
</style>
</head>
<body>
<h2>Click Write Cookie to save your cookie data.</h2>
<form method = "post" action = "Cookies_display.php">
<div><label>Name:</label>
<input type = "text" name = "name"><div>
<div><label>Height:</label>
<input type = "text" name = "height"></div>
<div><label>Favorite Color:</label>
<input type = "text" name = "color"></div>
<p><input type = "submit" value = "Write Cookie">
</form>
</body>
</html>

Cookies_display.php

<!DOCTYPE html>
<html>
<head>
<title>Displaying Cookie</title>
</head>
<body>

<?php
define( "FIVE_DAYS", 60 * 60 * 24 * 5 ); // define constant

// write each form field’s value to a cookie and set the


// cookie’s expiration date
setcookie("Name", $_POST["name"],time()+FIVE_DAYS);
setcookie("Height", $_POST["height"],time()+FIVE_DAYS );

setcookie("Color", $_POST["color"], time()+ FIVE_DAYS );

foreach ($_COOKIE as $key => $value )


print( "<h1>$key: $value</h1>" );
?>

</body>
</html>

Output

WT – UNIT IV – R19 Page 24


PHP and Web Forms

• FORM : A webform, web form or HTML form on a web page allows a user to enter data
that is sent to a server for processing

Methods:

• GET - $_GET($name)

POST - $_POST($name)

Form1.php

<html>
<head>
<title>Date Example
</title>
</head>
<body>

<form action="forms2.php" method="post">


<p>
Name: <br />
<input type="text" name="username" size="20"
maxlength="40" />
</p>
<p>
Email Address:<br />
<input type="text" name="email" size="20"
maxlength="40" />
</p>
<input type="submit" name="submit" value="Submit!" />
</p>
WT – UNIT IV – R19 Page 25
</form>
</body>
</html>

Form2.php

<html>
<head>
<title>Form Example
</title>
</head>
<body>
<?php
// If the name field is filled in
if (isset($_POST['submit'])) //
{
$name = $_POST['username'];
$email = $_POST['email'];
printf("Hi %s! <br />", $name);
printf("The Email address is - %s <br />", $email);
}
?>
</body>
</html>

POST Method

• http://localhost:90/forms2.php

GET Method

• http://localhost:90/forms2.php?name=CSE&email=1234%40gmail.com&submit=Go%21

PHP – CONNECTING to DATABASE

There are 5 steps to be followed in connecting to the database

1. Register Driver
2. Create connection
3. Create statement object
4. Execute Query
5. Close the connection

Example

data.php

<!DOCTYPE html>

<!-- Form to query a MySQL database. -->

WT – UNIT IV – R19 Page 26


<html>

<head>

<title>Sample Database Query</title>

</head>

<body>

<h1>Querying a MySQL database.</h1>

<form method = "post" action = "database.php">

<p>Select a field to display:

<!-- add a select box containing options -->

<!-- for SELECT query -->

<select name = "select">

<option selected>*</option>

<option>ID</option>

<option>Title</option>

<option>Category</option>

<option>Author</option>

</select></p>

<p><input type = "submit" value = "Send Query"></p>

</form>

</body>

</html>

Query_db_display.php

<!DOCTYPE html>

<!-- Querying a database and displaying the results. -->

<html>

<head>

<title>Search Results</title>

WT – UNIT IV – R19 Page 27


<style type = "text/css">

body { font-family: sans-serif;

background-color: lightyellow; }

table { background-color: lightblue;

border-collapse: collapse;

border: 1px solid gray; }

td { padding: 5px; }

tr:nth-child(odd) {

background-color: white; }

</style>

</head>

<body>

<?php

include 'db_connection.php';

$select = $_POST["select"]; // creates variable $select

// build SELECT query

$query = "SELECT " . $select . " FROM books";

// Connect to MySQL

if(!( $database = mysql_connect()))

die("Could not connect to database </body></html>");

// query books database

if(!( $result = mysql_query( $query, $database)))

print( "<p>Could not execute query!</p>");

die( mysql_error() . "</body></html>" );

} // end if

mysql_close( $database);

?><!-- end PHP script -->

<table>

WT – UNIT IV – R19 Page 28


<caption>Results of "SELECT <?php print("$select")?>

FROM books"</caption>

<?php

// fetch each record in result set

while($row = $result->fetch_assoc())

// build table to display results

print( "<tr>" );

foreach ( $row as $key => $value )

print( "<td>$value</td>" );

print( "</tr>" );

} // end while

?><!-- end PHP script -->

</table>

<p>Your search yielded

<?php print($result->num_rows) ?> results.</p>

</body>

</html>

mysql_db_connection.php

<?php

function mysql_connect()

$dbhost = "localhost";

$dbuser = "WIT";

$dbpass = "WIT";

$db = "WIT";

$conn = new mysqli($dbhost, $dbuser, $dbpass,$db)

or die("Connect failed: %s\n". $conn -> error);

WT – UNIT IV – R19 Page 29


return $conn;

function mysql_close($conn)

$conn -> close();

function mysql_query($query,$conn)

$result = $conn->query($query);

return $result;

function mysql_error()

echo "Unable to execute the query";

?>

XML (Extensible Markup Language)

• The Extensible Markup Language (XML) was developed in 1996 by the World Wide Web
Consortium’s (W3C’s) XML Working Group.

• XML is a widely supported open technology (i.e., non-proprietary technology) for


describing data that has become the standard format for data exchanged between applications
over the Internet.

• XML describes data in a way that human beings can understand and computers can process.

Rules of XML

• Can have our own tag names.


• Open and closing tags
• Must have root tag

Uses of XML / Why xml


• Transfer data
• Configuration files (web.xml, spring.xml, struts.xml)
• Design files ( Android projects)
• XML documents are highly portable.
o XML is Platform Independent and Language Independent

WT – UNIT IV – R19 Page 30


o The main benefit of xml is that you can use it to take data from a program like
Microsoft SQL, convert it into XML then share that XML with other programs and
platforms.
o We can communicate between two platforms which are generally very difficult.
XML features and advantages
• XML separates data from HTML
• XML simplifies data sharing
• XML simplifies data transport
• XML simplifies Platform change (system upgradation)
• XML can be used to create new internet languages
o XHTML
o WSDL

XML Structure
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

Example:

<Library>
<book cateogry="Techniccal">
<title>CP</title>
<author gender="M">James</author>
<cost>500</cost>
</book>
<book cateogry="Science">
<title>Physics</title>
<author gender="M">Roy</author>

<cost>600</cost>
</book>
</Library>

WT – UNIT IV – R19 Page 31


XML elements

• XML documents delimit elements with start tags and end tags.
• start tag consists of the element name in angle brackets
• An end tag consists of the element name preceded by a forward slash (/) in angle
brackets
• Every XML document must have exactly one root element that contains all the other
elements.

Viewing and Modifying XML docs

• To view and modify an XML document, we just need a Simple Text Editor with ASCII /
Unicode character support.
Example
Notepad++

XML attributes

• XML elements can have attributes. By the use of attributes we can add the information about
the element.
• XML attributes enhance the properties of the elements.
• XML attributes must always be quoted. We can use single or double quote.
<book publisher="Tata McGraw Hill"></book>

XML comments & Validation

<!-- Write your comment-->

XML Validation
• https://www.xmlvalidation.com/index.php?id=1&L=0

XML DOM

➢ It is a standard document model that is used to access and manipulate XML. It defines the
XML file in tree structure.
➢ This hierarchical tree structure is called a Document Object Model (DOM) tree, and an XML
parser that creates this type of structure is known as a DOM parser.

WT – UNIT IV – R19 Page 32


XML vs HTML

XML and HTML were designed with different goals:


• XML was designed to carry data - with focus on what data is
• HTML was designed to display data - with focus on how data looks
• XML tags are not predefined like HTML tags are

XML Related Technologies

• XHTML - Extensible HTML - is a stricter and cleaner version of HTML.


• XSL (Extensible Style Sheet Language)
• XSLT (XSL Transformations) is used to transform XML documents into other XML
formats, like XHTML.
• SOAP (Simple Object Access Protocol) is an XML-based protocol to let applications
exchange information over HTTP.
• WSDL (Web Services Description Language) is an XML-based language for describing web
services.
• RSS (Really Simple Syndication) is a format for syndicating news and the content of news-
like sites.
• DTD (Document Type Definition) is used to define the legal elements in an XML
document.
• XSD (XML Schema) is an XML-based alternative to DTDs.

Specifying XML document structure

To specify XML document structure, we use two methods :


1. DTD

WT – UNIT IV – R19 Page 33


2. XSD (XML Schema Document)

1. Document Type Definitions (DTDs)

• A DTD describes the structure of an XML document and enables an XML parser to verify
whether an XML document is valid (i.e., whether its elements contain the proper attributes
and appear in the proper sequence).
• A DTD expresses the set of rules for document structure using an EBNF (Extended Backus-
Naur Form) grammar.

Creating a Document Type Definition

<!DOCTYPE letter SYSTEM "letter.dtd">


• This DTD specifies the business letter’s element types and attributes and their relationships
to one another.

Example

<?xml version = "1.0"?>

<!-- Library.xml -->


<!-- Library data marked up with XML -->
<!DOCTYPE library SYSTEM "library.dtd">

<library>
<book BookId="101">
<title>CP</title>
<auth>Kan</auth>
<publisher>B</publisher>
<yop>2010</yop>
<price>2000</price>
</book>
<member MemberId="M01">
<name>Rahul</name>
<address>Kadapa</address>
<phone>9555</phone>
</member>
<staff StaffId="S01">
<name>GS</name>
<address>CHN</address>
<phone>2345</phone>
</staff>
<author AuthorId="A01">
<name>VVS</name>
<address>VJA</address>
<phone>1456</phone>
</author>
</library>

Library.dtd file

<!-- library.dtd -->


WT – UNIT IV – R19 Page 34
<!-- DTD document for Library_data.xml -->

<!ELEMENT library (book, member, staff,author)>

<!ELEMENT book (title, auth, publisher, yop,price)>

<!ATTLIST book BookId CDATA #IMPLIED>

<!ELEMENT title (#PCDATA)>


<!ELEMENT auth (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT yop (#PCDATA)>
<!ELEMENT price (#PCDATA)>

<!ELEMENT member (name, address, phone)>

<!ELEMENT staff (name, address, phone)>

<!ELEMENT author (name, address, phone)>

<!ATTLIST member MemberId CDATA #IMPLIED>


<!ATTLIST staff StaffId CDATA #REQUIRED>
<!ATTLIST author AuthorId CDATA #IMPLIED>

<!ELEMENT name (#PCDATA)>


<!ELEMENT address (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

• ATTLIST declaration can include #IMPLIED , #REQUIRED , and #FIXED.

• Keyword #IMPLIED specifies that if the parser finds a contact element without a type
attribute, the parser can choose an arbitrary value for the attribute or can ignore the attribute.

• Keyword #REQUIRED specifies that the attribute must be present in the element.

• Keyword #FIXED specifies that the attribute (if present) must have the given fixed value.

<!ATTLIST address zip CDATA #FIXED "01757">

• Character Data vs. Parsed Character Data

o Keyword CDATA (line 9) specifies that attribute type contains character data
(i.e., a string).

o A parser will pass such data to an application without modification.

o Keyword #PCDATA specifies that an element (e.g., name) may contain parsed
character data (i.e., data that’s processed by an XML parser).

• Parsed Character Data cannot contain markup characters, such as less than (<), greater than
(>) or ampersand (&).

o < must be replaced with &lt;

WT – UNIT IV – R19 Page 35


o > must be replaced with &gt;

o & must be replaced with &amp;

• The document author should replace any markup character in a #PCDATA element with the
character’s corresponding character entity reference.

XSD (XML Schema Document)

➢ It is a XML document.

➢ It does not use EBNF

➢ it has the feature to describe the data types

<element name = “quantity" type = "int"/>

Validation

www.xmlforasp.net/SchemaValidator.aspx

XSL and XSLT

• XSL - Extensible Stylesheet Language

• Extensible Stylesheet Language (XSL) documents specify how programs are to render
XML document data.

• XSL is a group of three technologies—

o XSL-FO (XSL Formatting Objects),

o XPath (XML Path Language) and

o XSLT (XSL Transformations).

• XSL-FO : XSL-FO is a vocabulary for specifying formatting

• XPath is a string-based language of expressions used by XML and many of its related
technologies for effectively and efficiently locating structures and data (such as specific
elements and attributes) in XML documents.

• XSL Transformations (XSLT)—is a technology for transforming XML documents into other
documents—i.e., transforming the structure of the XML document data to another structure.

o For example, XSLT allows you to convert a simple XML document to an XHTML
document that presents the XML document’s data (or a subset of the data) formatted
for display in a web browser.

Ex:

WT – UNIT IV – R19 Page 36


WT – UNIT IV – R19 Page 37
<xsl-stylesheet version = "1.0“ xmlns:xsl = http://www.w3.org/1999/XSL/Transform>

XML Namespaces
• An XML namespace is a collection of element and attribute names.

• XML namespaces provide a means for document authors to unambiguously refer to


elements with the same name (i.e., prevent collisions).

✓ XML-namespace reserved attribute xmlns to create two namespace prefixes—text and


image.

✓ Each namespace prefix is bound to a series of characters called a Uniform Resource


Identifier (URI) that uniquely identifies the namespace.

✓ Document authors create their own namespace prefixes and URIs.

✓ A URI is a way to identifying a resource, typically on the Internet.

✓ Two popular types of URI are Uniform Resource Name (URN) and Uniform Resource
Locator (URL).

<subject>Geometry</subject>

<subject>Cardiology</subject>

<highschool:subject>Geometry</highschool:subject>

<medicalschool:subject>Cardiology</medicalschool:subject>

WT – UNIT IV – R19 Page 38


XML Parsers

✓ Processing an XML document requires software called an XML parser (or XML
processor).

✓ A parser makes the document’s data available to applications.While reading an XML

✓ Document’s contents, a parser checks that the document follows the syntax rules
specified by the W3C’s XML Recommendation (www.w3.org/XML).

✓ XML parser is used to read, update, create and manipulate an XML document

o DOM: Document Object Model


o SAX: Simple API for XML

News Feed (RSS and ATOM)

• Content Syndication is a mechanism using which the contents of a website including articles,
news, blogs and forums are published partially or fully to other websites in a specific format.
• RSS and Atom are the two main standards of web syndication.

What’s a “feed”?

• RSS feed and ATOM feed are small text files that provide information about content on
websites.
• When content is updated, the feed text file is also updated, either manually or
programmatically.
• Applications called “readers” or “aggregators” can then check these small text files and
notify someone when new content is available.
• If you already have an RSS feed, creating an Atom feed is extremely easy.

RSS (Really Simple Syndication)

• With RSS it is possible to distribute up-to-date web content from one web site to thousands
of other web sites around the world.
• RSS allows fast browsing for news and updates.
• RSS stands for Really Simple Syndication

<?xml version="1.0" encoding="UTF-8" ?>


<rss version="2.0">

<channel>
<title>W3Schools Home Page</title>
<link>https://www.w3schools.com</link>
<description>Free web building tutorials</description>
<item>
<title>RSS Tutorial</title>
<link>https://www.w3schools.com/xml/xml_rss.asp</link>
WT – UNIT IV – R19 Page 39
<description>New RSS tutorial on W3Schools</description>
</item>
<item>
<title>XML Tutorial</title>
<link>https://www.w3schools.com/xml</link>
<description>New XML tutorial on W3Schools</description>
</item>
</channel>
</rss>

What is ATOM?

• Atom is the name of an XML-based Web content and metadata syndication format, and an
application-level protocol for publishing and editing Web resources belonging to periodically
updated websites.
• All Atom feeds must be well-formed XML documents, and are identified with
the application/atom+xml media type.

<?xml version="1.0" encoding="utf-8"?>


<feed xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02</updated>
<author>
<name>John Doe</name>
</author>
<entry>
<title>Atom-Powered Robots Run Amok</title>

<link href="http://example.org/2003/12/13/atom03"/>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>

</feed>

WT – UNIT IV – R19 Page 40

You might also like