0% found this document useful (0 votes)
25 views35 pages

Chap 5 Web Extension

Ip chap 5

Uploaded by

SHREYA BHUVAD
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)
25 views35 pages

Chap 5 Web Extension

Ip chap 5

Uploaded by

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

5 – Web Extension: PHP and XML

XML
What is XML?
 XML is a meta-language, which can be used to store data & act as a mechanism to transfer
information between dissimilar systems.
 XML stands for EXtensible Markup Language.
 XML is a markup language much like HTML.
 XML was designed to describe data.
 XML tags are not predefined in XML. You must define your own tags.
 XML is self describing.
 XML uses a DTD (Document Type Definition) to formally describe the data.

<?xml version=”1.0”?>
<Person>
<Firstname>Ralph</Firstname>
<Lastname>Mosely</Lastname>
</Person>

Difference between XML and HTML


XML HTML
XML was designed to store data and transferthe HTML was designed to display data.
data.
XML focuses on what data is. HTML focus on how data looks.
In XML you can design your own tag. HTML has predefined tags.
XML uses parser to check & read xml fileseg. DOM, HTML don’t use any kind of parser
SAX

Use of XML
 Used to exchange data between dissimilar systems.
 Used to describe content of document.
 XML can be used as database to store data.

Features of XML
 XML has its own tag so it’s self describing.
 Language Independent:Any language is able to read & write XML.
 OS Independent: can be work on any platform.
 Readability: It’s a plain text file in user readable format so you can edit or viewin simple editor.

1
5 – Web Extension: PHP and XML
 Hierarchical: It has hierarchical structure which is powerful to express complex data and simple to
understand.

XML Key Component


1.) XML Root Element
o XML must have root element. The first element after xml version declaration in file is a root
element.

<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>

o In above example <bookstore> is root element.

2.) XML Element


o An XML element is everything from (including) the element's start tag to (including) the
element's end tag.
o An element can contain:
 other elements
 text
 attributes
 or a mix of all of the above...
o In above example <title>, <author>, <year> and <price> are elements.

3.) XML Attribute


o Attributes provide additional information about an element.
o Attributes often provide information that is not a part of the data. In the example below,the
file type is irrelevant to the data, but can be important to the software that wants to
manipulate the element

<file type="gif">computer.gif</file>

o XML Attributes Must be Quoted


o Attribute values must always be quoted. Either single or double quotes can be used. For a
person's sex, the person element can be written like this:

<person sex="female"> or <person sex='female'>

1
5 – Web Extension: PHP and XML
4.) XML Namespace
o The XML namespace is a special type of reserved XML attribute that you place in an XML tag.
o The reserved attribute is actually more like a prefix that you attach to any namespace you
create.
o This attribute prefix is "xmlns:” which stands for XML Namespace.
o The colon is used to separate the prefix from your namespace that you are creating.
o xmlns must have a unique value that no other namespace in the document has. What is
commonly used is the URI (Uniform Resource Identifier) or the more commonly used URL.

Xmlns=”http://www.mydomian.com/ns/animals/1.1”

Create a XML file that contains Book Information.


<xml version=”1.0”?>
<bookstore>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book>
<title>WAD</title>
<author>Ralph Mosely</author>
<year>2001</year>
<price>395</price>
</book>
</bookstore>

DTD (Document Type Definition)


 The purpose of a DTD is to define the legal building blocks of an XML document. Itdefines the
document structure with a list of legal elements. A DTD can be declaredinline in your XML
document, or as an external reference.
 Internal DTD
o This is an XML document with a Document Type Definition:

1
5 – Web Extension: PHP and XML

<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Ravi</to>
<from>Ketan</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

o The DTD is interpreted like this:


 !ELEMENT note (in line 2) defines the element "note" as having four elements:
"to,from,heading,body".
 !ELEMENT to (in line 3) defines the "to" element to be of the type "CDATA".
 !ELEMENT from (in line 4) defines the "from" element to be of the type "CDATA"
 External DTD
o This is the same XML document with an external DTD

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Ravi</to>
<from>Narendra</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

o This is a copy of the file "note.dtd" containing the Document Type Definition:

1
5 – Web Extension: PHP and XML

<?xml version="1.0"?>
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

DTD - Elements
 In the DTD, XML elements are declared with an element declaration. An element declaration has the
following syntax:

<!ELEMENT element-name (element-content)>

 Empty elements
o Empty elements are declared with the keyword EMPTY inside the parentheses:

<!ELEMENT img (EMPTY)>


 Elements with data
o Elements with data are declared with the data type inside parentheses:

<!ELEMENT element-name (#CDATA)>


or
<!ELEMENT element-name (#PCDATA)>
or
<!ELEMENT element-name (ANY)>
example:
<!ELEMENT note (#PCDATA)>

o #CDATA means the element contains character data that is not supposed to be parsed bya
parser.
o #PCDATA means that the element contains data that IS going to be parsed by a parser.
o The keyword ANY declares an element with any content.
o If a #PCDATA section contains elements, these elements must also be declared.
 Elements with children (sequences)
o Elements with one or more children are defined with the name of the children
elementsinside the parentheses:

1
5 – Web Extension: PHP and XML

<!ELEMENT element-name (child-element-name)>


or
<!ELEMENT element-name (child-element-name,child-element-name,. )>
example:
<!ELEMENT note (to,from,heading,body)>

o When children are declared in a sequence separated by commas, the children must appearin
the same sequence in the document. In a full declaration, the children must also bedeclared,
and the children can also have children. The full declaration of the notedocument will be:

<!ELEMENT note (to,from,heading,body)>


<!ELEMENT to (#CDATA)>
<!ELEMENT from (#CDATA)>
<!ELEMENT heading (#CDATA)>
<!ELEMENT body (#CDATA)>

 Wrapping
o If the DTD is to be included in your XML source file, it should be wrapped in aDOCTYPE
definition with the following syntax:

<!DOCTYPE root-element [element-declarations]>


example:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#CDATA)>
<!ELEMENT from (#CDATA)>
<!ELEMENT heading (#CDATA)>
<!ELEMENT body (#CDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body></note>

 Declaring only one occurrence of the same element

1
5 – Web Extension: PHP and XML

<!ELEMENT element-name (child-name)>


example
<!ELEMENT note (message)>

o The example declaration above declares that the child element message can only occurone
time inside the note element.
 Declaring minimum one occurrence of the same element

<!ELEMENT element-name (child-name+)>


example
<!ELEMENT note (message+)>
o The + sign in the example above declares that the child element message must occur oneor
more times inside the note element.
 Declaring zero or more occurrences of the same element

<!ELEMENT element-name (child-name*)>


example
<!ELEMENT note (message*)>

o The * sign in the example above declares that the child element message can occur zeroor
more times inside the note element.
 Declaring zero or one occurrences of the same element

<!ELEMENT element-name (child-name?)>


example
<!ELEMENT note (message?)>

o The? Sign in the example above declares that the child element message can occur zeroor
one times inside the note element.

DTD – Attributes
 Attributes provide extra information about elements.
 Attributes are placed inside the start tag of an element.
 Declaring Attributes
o In the DTD, XML element attributes are declared with an ATTLIST declaration. Anattribute
declaration has the following syntax:

<!ATTLIST element-name attribute-name attribute-type default-value>

o As you can see from the syntax above, the ATTLIST declaration defines the elementwhich
can have the attribute, the name of the attribute, the type of the attribute, and thedefault
attribute value.
o The attribute-type can have the following values:

1
5 – Web Extension: PHP and XML
Value Explanation
CDATA The value is character data
(eval|eval|..) The value must be an enumerated value
ID The value is an unique id
IDREF The value is the id of another element
IDREFS The value is a list of other ids
NMTOKEN The value is a valid XML name
NMTOKENS The value is a list of valid XML names
ENTITY The value is an entity
ENTITIES The value is a list of entities
NOTATION The value is a name of a notation
xml: The value is predefined

o The attribute-default-value can have the following values:


Value Explanation
#DEFAULT value The attribute has a default value
#REQUIRED The attribute value must be included in the
element
#IMPLIED The attribute does not have to be included
#FIXED value The attribute value is fixed

 Attribute declaration example

DTD example:
<!ELEMENT square EMPTY>
<!ATTLIST square width CDATA "0">
XML example:
<square width="100"></square>

o In the above example the element square is defined to be an empty element with
theattributes width of type CDATA. The width attribute has a default value of 0.

XML Schema
 An XML Schema describes the structure of an XML document.
 XML Schema is an XML-based alternative to DTD.
 The XML Schema language is also referred to as XML Schema Definition (XSD).
 XML Schema is a W3C Recommendation.

XSD Elements
 XML Schemas define the elements of your XML files. It’s of two types:
o Simple
o Complex Type

1
5 – Web Extension: PHP and XML
XSD Simple Elements
 A simple element is an XML element that can contain only text. It cannot contain any other elements
or attributes.
 Defining a Simple Element
o The syntax for defining a simple element is:

<xs:element name="aaa" type="bbb"/>


o Where aaa is the name of the element and bbb is the data type of the element.
o XML Schema has a lot of built-in data types. The most common types are:
 xs:string
 xs:decimal
 xs:integer
 xs:Boolean
 xs:date
 xs:time
 Example
o Here are some XML elements:

<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>

o And here are the corresponding simple element definitions:

<xs:element name="lastname" type="xs:string"/>


<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>

XSD Complex Elements


 A complex element is an XML element that contains other elements and/or attributes.
 There are four kinds of complex elements:
o empty elements
o elements that contain only other elements
o elements that contain only text
o elements that contain both other elements and text
 Examples of Complex Elements
o A complex XML element, "product", which is empty:

<product pid="1345"/>
o A complex XML element, "employee", which contains only other elements:

1
5 – Web Extension: PHP and XML

<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

o A complex XML element, "food", which contains only text:

<food type="dessert">Ice cream</food>


o A complex XML element, "description", which contains both elements and text:

<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>

XSD Attributes
 Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type.
 How to Define an Attribute?
o The syntax for defining an attribute is:

<xs:attribute name="aaa" type="bbb"/>


o Where aaa is the name of the attribute and bbb specifies the data type of the attribute.
 Default and Fixed Values for Attributes
o Attributes may have a default value OR a fixed value specified.
o A default value is automatically assigned to the attribute when no other value is specified.
o In the following example the default value is "EN":

<xs:attribute name="lang" type="xs:string" default="EN"/>


o A fixed value is also automatically assigned to the attribute, and you cannot specifyanother
value.
o In the following example the fixed value is "EN":

<xs:attribute name="lang" type="xs:string" fixed="EN"/>

 Optional and Required Attributes


o Attributes are optional by default. To specify that the attribute is required, use the
"use"attribute:

<xs:attribute name="lang" type="xs:string" use="required"/>

Difference between DTD and XML Schema

XML Schema DTD


Markup Any global element can be root. Can specify only the root
10
5 – Web Extension: PHP and XML
validation No ambiguous content support. element in the instance
document. No ambiguous
content support.
Namespace Yes. Declarations only where No.
support multiple namespaces are used.
Code reuse Can reuse definitions using Poorly supported. Can use
named types. parameter entities.
Data type Provides flexible set of data types. No real data type support.
Validation Provides multi-field key cross
references. No co-occurrence
constraints.

XSL

What is XSL?
 XSL stands for EXtensible Stylesheet Language.
 XSL = Style Sheets for XML
 XSL describes how the XML document should be displayed!
 XSL - More Than a Style Sheet Language
 XSL consists of three parts:
o XSLT-a language for transforming XML documents
o XPath-a language for navigating in XML documents
o XSL-FO-a language for formatting XML documents

What is XSLT?
 XSLT stands for XSL Transformations.
 XSLT is the most important part of XSL.
 XSLT transforms an XML document into another XML document.
 XSLT uses XPath to navigate in XML documents.

Explain XSL Transformation and XSL Elements


 The style sheet provides the template that transforms the document from one structure to another.
 In this case <xsl:template> starts the definition of the actual template, as the root of the source XML
document.
 The match = “/” attribute makes sure this begins applying the template to the root of the source
XML document.

Linking
 The style sheet is linked into the XML by adding the connecting statement to the XML document:
<?xml-stylesheet type=”text/xsl” href=”libstyle.xsl” ?>
XSL Transformations
 XSLT is the most important part of XSL.
 XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by
transforming each XML element into an (X)HTML element.
 With XSLT you can add/remove elements and attributes to or from the output file. You can also

11
5 – Web Extension: PHP and XML
rearrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.
 A common way to describe the transformation process is to say that XSLT transforms an XML
source-tree in to an XML result-tree.
 XSLT Uses XPath:
o XSLT uses XPath to find information in an XML document.
o XPath is used to navigate through elements and attributes in XML documents.
 XSLT Works as:
o In the transformation process, XSLT uses XPath to define parts of the source document
that should match one or more predefined templates.
o When a match Is found, XSLT will transform the matching part of the source document
into the result document.

XSL Elements
 XSL contains many elements that can be used to manipulate, iterate and select XML, for output.
o value-of
o for-each
o sort
o if
o choose

<xsl:value•of> Element
 The <xsl:value-of> element extracts the value of a selected node.
 The <xsl:value-of> element can be used to select the value of an XML element and add it to the
output.
 Syntax
<xsl:value-of select="expression" />
o expression: This is Required. An XPath expression that specifies which node/attribute to
extract the value from. It works like navigating a file system where a forward slash (/) selects
subdirectories.

<xsl:for•each> Element
 The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set.

<xsl:if> Element
 To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL
document.
 Syntax
<xsl:if test="expression">
...some output if the expression is
true...
</xsl:if>

<xsl:sort> Element
 The <xsl:sort> element is used to sort the output.
 <xsl:sort select="artist"/>
 The select attribute indicates what XML element to sort on.

11
5 – Web Extension: PHP and XML
Example using value•of, for•each and if

<?xml version="1.0" encoding="ISO-8859-1"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:if test="price &gt; 10">
<tr>
<td>
<xsl:value-of select="title"/>

</td>
<td><
xsl:value-of select="artist"/>

</td>

</tr>

</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

<xsl:choose> Element
 The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express
multiple conditional tests.

11
5 – Web Extension: PHP and XML
 Syntax
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>

<xsl:apply-templates> Element
 The <xsl:apply-templates> element applies a template to the current element or to the current
element's child nodes.
 If we add a select attribute to the <xsl:apply-templates> element it will process only the child
element that matches the value of the attribute. We can use the select attribute to specify the order
in which the child nodes are processed.
 Look at the following XSL style sheet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="cd">
<p>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
</xsl:stylesheet>

Explain transforming with XSLT.


 It is possible to convert an XML document to XHTML using the browser’s own parser. However, this
is not always possible:
o The browser at the client end may not be suitable or equipped to do the transformation.
o It may not be a good idea to include the reference to the style sheet or even have the style

11
5 – Web Extension: PHP and XML
sheet available!
 The answer to this process the document and style sheet outside of the browser’s own mechanism
for doing this task.
 This task can be done either on the client side or the server side.

Using JavaScript
 One way to process and transform XML on the client side is using JavaScript, which has several
features for doing the task very well.
<html>
<body>
<script type=”text/javascript”>
//Load the XML document
var xml= new ActiveXObject(“Microsoft.XMLDOM”)
xml.async=false
xml.load(“lib.xml”)
//Load the XSL document
var xsl= new ActiveXObject(“Microsoft.XMLDOM”)
xsl.async= false
xsl.load(“libstyle.xsl”)
//Do the actual transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

 Above example shows one way to transform with JavaScript using Microsoft’s proprietary
Application Programming Interface (API) for the Internet Explorer browser.
 It is also possible to process XML using the DOM.
 Using both the of these mechanisms it is possible to also traverse an XML document and process
either according to a style sheet or simply using the JavaScript to make the stylistic decisions.
 Apart from JavaScript, it is also possible to use other programming languages (such as Java and .Net)
to process and then output a transformed document.

11
5 – Web Extension: PHP and XML

History of PHP, Apache Web Server, MySQL and Open Source


Open Source
 In general, open source refers to any program whose source code is made available for use or
modification.
Open source software is usually developed as a public collaboration and made freely available. It
means can be used without purchasing any license.
 Open Source is a certification mark owned by the Open Source Initiative (OSI). Developers of
software that is intended to be freely shared and possibly improved and redistributed by others can
use the Open Source trademark if their distribution terms conform to the OSI's Open Source
Definition. To summarize, the Definition model of distribution terms require that:
 The software being distributed must be redistributed to anyone else without any restriction.
 The source code must be made available (so that the receiving party will be able to improve
or modify it).
 Example of Open Source: Linux, Apache, MySQL, PHP.

PHP
 PHP is a general-purpose server-side scripting language originally designed for web development to
produce dynamic websites.
 PHP scripts execute on web server and serve WebPages to user on request.
 PHP was originally created by RasmusLerdorf in 1994. Programmer RasmusLerdorf initially created a
set of C scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts
performed tasks such as displaying his résumé and recording his web-page traffic.
 These were released and extended to include a package called the Form Interpreter (PHP/FI). While
PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext
Preprocessor", a recursive acronym.
 PHP code is embedded into the HTML source document and interpreted by a web server with a PHP
processor module, which generates the web page document. It also has evolved to include a
command-line interface capability and can be used in standalone graphical applications.PHP can be
deployed on most web servers and as a standalone interpreter, on almost every operating system
and platform free of charge.
 In 1997 ZeevSuraski and AndiGutmans along with Rasmus rewrite PHP and released PHP version 3.0
in June 1998.After this release PHP becomes so much popular.
 The PHP version 4.0 was launched in May 2000.This version includes session handling, output
buffering, a richer cire language and support for wide variety of web server platforms.
 The PHP 5.0 version released in 2004 with object oriented programming concept.

Web Server
 A Web Server is computer and the program installed on it. Web Server interacts with the client
through the browser. It delivers the web pages to the client and to an application by using the web
browser and HTTP protocol respectively.
 We can also define the web server as the package of larger number of programs installed on a
computer connected to internet or intranet for downloading the requested files using File Transfer
Protocol, serving e- mail and building and publishing web pages.

10
5 – Web Extension: PHP and XML
 A web server works on client server model. A computer connected to internet or intranet must have
a server program.
 A computer connected to the internet for providing the services to a small company or a department
store may contain the HTTP server to access and store WebPages and files, SMTP server to support
mail services, FTP server for files downloading and NNTP server for newsgroup.
 The computer containing all the above servers is called the web server.

Apache Web Server


 The Apache web Server, commonly referred to as Apache is web server software notable for playing
a key role in the initial growth of the World Wide Web.
 The first version of Apache, based on the NCSA httpd Web server, was developed in 1995. The
Apache server has been developed by an open source community - Apache Software Foundation,
whose members are constantly adding new useful functionalities, with the sole purpose of providing
a secure and extensible server platform that ensures HTTP service delivery in accordance with the
current HTTP standards.
 The original version of Apache was written for UNIX, but there are now versions that run under
OS/2, Windows and other platforms.
 The Apache Server provides full range of Web Server features, including CGI, SSL and virtual
domains. Apache also supports plug-in modules for extensibility.
 It was called Apache because it was developed from existing NCSA code plus various patches, hence
the name a patchy server, or Apache server.
 Apache is open source free software distributed by the Apache Software Foundation.
 Apache is reliable, free and relatively easy to configure.

MySQL
 MySQL is a relational database management system (RDBMS) that runs as a server providing
multi-user access to a number of databases.
 It is named after developer Michael Widenius' daughter, My. The SQL phrase stands for Structured
Query Language.
 The data in MySQL is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.
 The MySQL development project has made its source code available under the terms of the License.
The license can require improved versions of the software to carry a different name or version from
the original software.
 First released in January,1998, MySQL was owned and sponsored by the Swedish company MySQL
AB, now owned by Oracle Corporation.
 MySQL is fully multithreaded using kernel threads, and provides application programming interfaces
(APIs) for many programming languages, including C,C++, Java, Perl, PHP, Python.
 MySQL is used in a wide range of applications, including data warehousing, e-commerce, Web
databases, logging applications and distributed applications.

10
5 – Web Extension: PHP and XML
Relationship between Apache, MySQL and PHP (AMP Module)
 AMP stands for Apache MySQL PHP

PHP
 PHP is a server side scripting that was designed for creating dynamic websites. It slots into your
Apache web server and processes instructions contained in a web page before that page is sent
through to your web browser.
 PHP is a powerful scripting language that can be run in the command line of any computer with
PHPinstalled. However, PHP alone isn't enough in order to build dynamic web sites.

Apache
 To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web
Server that, once installed on a computer, allows developers to test PHP scripts locally; this makes it
an invaluable piece of your local development environment.
 Like all web servers, Apache accepts an HTTP request and serves an HTTP response.

MySQL
 Additionally, dynamic websites are dependent on stored information that can be modified quickly
and easily; this is the main difference between a dynamic site and a static HTML site. However, PHP
doesn’t provide a simple, efficient way to store data. This is where a relational database
management system like MySQL comes into play. PHP provides native support for it and the
database is free, open-source project.
 MySQL is a relational database management system (DBMS). Essentially, this means that MySQL
allows users to store information in a table-based structure, using rows and columns to organize
different pieces of data.

Explain Array in PHP


Array is a group of variable that can store multiple values under a single name.

In PHP, there are two types of array.

 Numeric Array
 Associative Array
 Multidimensional Array

Numeric Array
 In numeric array each element having numeric key associated with it that is starting from 0;
 You can use array() function to create array.
 The general syntax is given below:
$array_name=array ( value1, value2 …valueN);
 For Example:

10
5 – Web Extension: PHP and XML

<?php $myarray=array(‘A’,’B’,’C’);
print_r($myarray);

?>

Output: Array( [0]=>A [1]=>B [2]=>C)

 You can refer to individual element of an array in PHP script using its key value as shown below:
<?php
$myarray=array(‘A’,’B’,’C’);
echo $myarray[1];
?>
It will display
B
 In Numeric Array you can use for, while or do while loop to iterate through each element in array
because in numeric array key values are consecutive.

<?php
$myarray=array(“Apache”, “MySQL”, “PHP”);
for($i=0;$i<3;$i++)
{
echo $myarray*$i+.”<br>”;
}
?>
Output:
Apache
MySQL
PHP

Associative Array
 The associative part means that arrays store element values in association with key values rather
than in a strict linear index order.
 If you store an element in an array, in association with a key, all you need to retrieve it later from
that array is the key value.
 Key may be either numeric or string.
 You can use array() function to create associative array.
 The general syntax is given below:
$array_name=array(key1=>value1, key1=>value1,….. keyN=>valueN);

10
5 – Web Extension: PHP and XML

For Example 1:
<?php $myarray=array(5=>”Apple”, 10=>”Mango”, 20=>”Grapes”);
print_r($my_array);

?>
Output:
Array([5]=>Apple [10]=>Mango [20]=>Grapes)
Example 2:
<?php
$myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
print_r($myarray);
?>
Output:
Array([Name]=>James [Age]=>25 [Gender]=>Male)

 You can refer to individual element of an array in PHP using its key value.

Example:
<?php $myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
echo “Name:”.$myarray*‘Name’+;

?>
Output:
Name:James

 In associative array you cannot use for, while r do..while loop to iterate through each element in
array because in Associative array key value are not consecutive.
 So you have to use foreach loop.

For Example:
<?php $myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
foreach($myarray as $item)
{

}
?>
Output:

10
5 – Web Extension: PHP and XML
echo $item;
James 25 Male

Multidimensional Array
PHP can easily support multidimensional arrays, with arbitrary numbers of key.And just as in one
dimensional arrays, there is no need to declare out intentions in advance. Assignment can be like:

10
5 – Web Extension: PHP and XML
$multi_array*0+*1+*2+*3+=”Good

Morning”; That is four dimensional array with

numerical index.

The values those are stored in array can themselves be arrays, just as legitimately as they can be string or
numbers.

For example:

$multi_level_array*0+=”a simple string”;


$multi_level_array*1+*‘contains’+=”a string stored deeper”;

The integer key of 0 stores a string, and the key 1 stores an array that ,in turn, has a string in it.

Creating array within another array using array() construct is as follows:

$basket=array( ‘fruit’ => array(‘red’ => ‘apple’,


‘yellow’ => ‘banana’,
‘black’ => ‘grapes’),
‘flower’ =>array(‘red’ => ‘rose’,
‘yellow’ => ‘sunflower’,
‘purple’ => ‘iris’)
);

It is simply an array with two values stored in association with keys.Each of them values is an array itself. We
can reference it like this

echo

$basket*‘fruit’+*‘black’+; will print

grapes. And

$kind=”flower”;
$color=”yellow”;
print(“ $basket *$kind+

*$color+”);will print sunflower.

10
5 – Web Extension: PHP and XML
How do you create session & cookie in PHP? Give difference between
session and cookie with example. OR
What are cookies? Explain the cookies handling in PHP with proper
example.

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

PHP Session Variables


 When you are working with an application, you open it, do some changes and then you close it.
 This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end.
 But on the internet there is one problem: the web server does not know who you are and what you
do because the HTTP address doesn't maintain state.
 A PHP session solves this problem by allowing you to store user information on the server for later
use (i.e. username, shopping items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent storage you may want to store
the data in a database.
 Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


 Before you can store user information in your PHP session, you must first start up the session.
 The session_start() function must appear BEFORE the <html> tag:

<?phpsession_start(); ?>
<html>
<body>
</body>
</html>

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

Storing a Session Variable


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

10
5 – Web Extension: PHP and XML

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

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

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session
 If you wish to delete some session data, you can use the unset() or the session_destroy() function.
 The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
 You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
 Note:session_destroy() will reset your session and you will lose all your stored session data.

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

How to Create a Cookie?


 The setcookie() function is used to set a cookie.
 Note: The setcookie() function must appear BEFORE the <html> tag.
setcookie(name, value, expire, path, domain);

 In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it.
We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....

 Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
 You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....

 In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?


 The PHP $_COOKIE variable is used to retrieve a cookie value.
 In the example below, we retrieve the value of the cookie named "user" and display it on a page:

10
5 – Web Extension: PHP and XML

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies


print_r($_COOKIE);
?>

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

<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>

</body>
</html>

How to Delete a Cookie?


 When deleting a cookie you should assure that the expiration date is in the past.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

What if a Browser Does NOT Support Cookies?


 If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to pass
the data through forms (forms and user input are described earlier in this tutorial).\
 The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
button:

10
5 – Web Extension: PHP and XML

<html>
<body>
<form action="welcome.php" method="post"> Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

 Retrieve the values in the "welcome.php" file like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

10
5 – Web Extension: PHP and XML

How can you connect to database in PHP? Show the simple database
operation using PHP with proper example.
Integration of PHP with MySQL
 It is possible to execute various commands of MySQL from PHP.PHP provides various built-in
functions which you allows you to use MySQL commands from PHP page. Thus you can integrate
PHP with MySQL.
 Following are the various PHP functions that allows you the facility of integrating PHP with MySQL:

mysql_connect()

 Before you can access data in a database, you must create a connection to the database.
 This function allows you to establish connection of PHP application with MySQL server.
 Syntax: mysql_connect(servername,username,password);

servername Indicates the name of MySQL server with which you want to establish
connection.
 It is optional .Default value is localhost:3306
UserName  Indicates the name of user using which you can logs on to MySQL Server.
 Optional. Default value is the name of the user that owns the server process.
Password  Indicates password of the user using which you can logs on to MySQL Server.
 It is optional. Default is "".
 If connection establish successfully with MySQL Server then this function returns TRUE value
otherwise it returns FALSE.
 Example
<?php
$conn=mysql_connect(“localhost”,”root”,””);
if($conn)
{
} echo “Connected with MySQL”;
else
{

} echo “Could not connect to database”;

?>

mysql_select_db()
 This function allows you to select database from the list of MySQL server databases.
 Syntax: mysql_select_db (DatabaseName, ConnectionName);

DatabaseName  Indicates the name of the database that you want to select.
ConnectionName  Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.

1
5 – Web Extension: PHP and XML
 If function successfully executed then it returns TRUE otherwise it returns FALSE.
 Example:

<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”);
if($db)
{
echo “Database Selected Successfully ”;
}
else
{
echo “Error in selecting Database.”;
}
?>

mysql_query()

 This function allows you to specify and execute the MySQL command on MySQL Server.
 Syntax:
mysql_query(Query, ConnectionName);

Query  Indicates the MySQL command to be executed.


ConnectionName  Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.

 Example

<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$cmd=mysql_query(“create table Test(ID integer, Name varchar(20))”);
if($cmd)
{

}
else
{

}
?>

1
5 – Web Extension: PHP and XML
echo “Table created
Successfully ”;

echo “Error in
executing query.”;

mysql_fetch_row()

 This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.

1
5 – Web Extension: PHP and XML
 The record that is returned by this function is in the form of numeric array. Numeric array contains
index and value associated with that index.
 If there is no record in the record set then it returns false value.
 Syntax:
mysql_fetch_row(VariableName);
 VariableName indicates the record set that is returned from executing the MySQL command using
mysql_query() function.
 Example:

<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query,$conn);
$ans=mysql_fetch_row($result);
print_r($ans);
mysql_close($con);

?>

mysql_fetch_array()

 This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.
 The record that is returned by this function is in the form of either numeric array, associative array
or both.
 If there is no record in record set then it will returns false value.
 Syntax:
mysql_fetch_array(VariableName, ResultArrayType)
 VariableName:- indicates the record set that is returned from executing the MySQL command
using mysql_query() function.
 ResultArrayType:-indicates the type of array to be returned. It can have one of the following
values:
MYSQL_ASSOC This type of array contains name of the field and the value associated with that
field for current record.
MYSQL_NUM This type of array contains index of the field and the value associcated with that
index for current record.
MYSQL_BOTH It is combination of both Associative array and Numeric array. It is the default
type to be returned by this function.

1
5 – Web Extension: PHP and XML
 Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_array($result,MYSQL_ASSOC);
print_r($ans);
mysql_close($con);

?>

mysql_fetch_assoc()

 This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query in the form of associative array.
 Syntax:
mysql_fetch_assoc(VariableName)
 Returns an associative array that corresponds to the fetched row, or FALSE if there are no more
rows.
 Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_assoc($result);
print_r($ans);
mysql_close($con);
?>

1
5 – Web Extension: PHP and XML
To go through all the records fetched in record set.

<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
while($ans=mysql_fetch_assoc($result))
{
echo $ans*‘field1’+.”<br>”;
echo $ans*‘field2’+.”<br>”;
}
mysql_close($con);
?>

mysql_num_rows()

 This function allows you to retrieve number of records available in the record set.
 Syntax:
mysql_num_rows(ResultVariable);
 ResultVariable is the variable that holds result returned by mysql_query() function.
 Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$total_records=mysql_fetch_rows($result);
echo “Total Records:”.$total_records;
mysql_close($con);
?>

mysql_error()

 This function allows you to retrieve theerror text from the most recently executed MySQL
function.
 If no error encountered while executing the script then it will returns blank string.
 If the mysql operation contains more than one error then it will returns error description of the
last statement in which error is encountered.
 Syntax:
mysql_error();

1
5 – Web Extension: PHP and XML
 Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
if($conn)
{

}
else
{

}
?>

1
5 – Web Extension: PHP and XML
echo “Connected with
MySQL”;

echo
“Error:”.mysql_error()
;

mysql_close()

 This function allows you to close the connection that is established using mysql_connect()
function.
 Syntax:mysql_close(ConnectionName);
 ConnectionName :- Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.
 It returns true is connection is closed successfully otherwise it returns false.
 Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
mysql_close($con);
?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy