USING DATABASES AND
HANDLING XML
INTRODUCTION
Relational databases are central to most of the commercial
Web development
Databases are used to store, manage and efficiently query
large volumes of data
They are complex pieces of software built on a relatively
simple programming model
Let us look at some of the database facilities which can be
used by PHP
NEED FOR WEB SERVERS
Need of web servers
Large scale Web systems are most often based on J2EE
A version of Java which has the features to run enterprise systems
J2EE is massively complex once it tires to be all things to all enterprises
Small organizations often use Microsoft products, uses .NET framework
It is rich and powerful but not fully featured asJ2EE
Disadvantages
Both are proprietary
Aimed at business developers
Have problems of complexity and bloat
Popular open source alternatives
Running on GNU / Linux OS
Apache Web server
MySQL database
Use of one popular programming languages PHP / Perl / Python
LAMP
The suite of technologies
Popular both together and individually
Installed free of charges
INTRODUCTION TO MYSQL
A great success story of open-source
Resource at www.mysql.com
Been around for a decade
Software downloaded over 100 million times
MySQL is overloaded – indicated two meanings
Database engine
Database software
USING MYSQL
Relational databases are manipulated using a language called
SQL
SQL commands can be used both from the MySQL interface
and from within PHP scripts
SQL scripts are not case sensitive
Commands end with a semicolon, but not when inside PHP
code
SHOW DATABASES;
Lists all of the databases which are available on the system
USE name
Selects one the available databases
CREATE DATABASE name
Creates an empty database with the name, supplied as parameter
DROP DATABASE name
Deletes the named database
CREATE TABLE
DELETE TABLE
COMMONLY USED DATABASE
BOOLEAN – non-zero values are true and zero is false
INTEGER [UNSIGNED] – holds integer values in the range of
+ / - 231
MEDIUM INT – holds integer values in the range of + / - 2 2 3 ,
unsigned integers can range from 0 to 2 3 4
DOUBLE[(m,b)]- is a double precision floating point number
accurate to 15 decimal places, if “m” is specified in parentheses it
indicates the display width of the number, “ b” represents the
precision
DECIMAL[(m,b)] [UNSIGNED] – indicates a decimal number, m gives
the total number if digits, “d” the number of decimals
DATE – a date in YYYY-MM-DD format
CHAR – an ASCII character
VARCHAR(m) – is a variable length using “m” gives the length of the
string in the range of 1 to 255
TEXT – a piece of text of max. length 65535 characters
ENUM(‘value’, [,’value2’[,……….,]]) an enumeration, a comma-
separated list of values, columns must take one of these values
ACCESSING MYSQL FROM PHP
Using and accessing database is a very complex activity
Let us consider a simple application which store name, email
address and role taken from a drop down list.
Data is entered in an HTML form
User queries the database, delete or amend the existing
records and add new data
KICK STARTING THE APPLICATION
1. Connection to the database
<?php
$db = mysqli_connect (‘localhost’, ‘username’, ‘password’,
‘database’);
if(!$db)
{
die(unable to connect to the database”,
mysqli_connect_error());
}
?>
2. Handling form elements
function handleForm()
{
$firstname =$_POST[‘firstname’];
$lastname = $_POST[‘lastname’];
$email = $_POST[‘email’];
$role = $_POST[‘role’];
}
OTHER METHODS
mysqli_query(database,statement)
mysqli_fetch_object(result)
mysqli_fetch_row(result)
mysqli_fetch_array(result,type)
WHAT IS XML
The XML language is a way to structure data for sharing
across websites.
Several web technologies like RSS Feeds and Podcasts are
written in XML.
XML is easy to create. It looks a lot like HTML, except that you
make up your own tags.
WHAT IS AN XML PARSER?
To read and update, create and manipulate an XML document,
you will need an XML parser.
In PHP there are two major types of XML parsers:
Tree-Based Parsers
Event-Based Parsers
TREE-BASED PARSER
Tree-based parsers holds the entire document in Memory
and transforms the XML document into a Tree structure
It analyzes the whole document, and provides access to
the Tree elements (DOM)
This type of parser is a better option for smaller XML
documents, but not for large XML document as it causes
major performance issues
Example of tree-based parsers:
SimpleXML
DOM
EVENT-BASED PARSERS
Event-based parsers do not hold the entire document in
Memory, instead, they read in one node at a time and allow
you to interact with in real time
Once you move onto the next node, the old one is thrown away
This type of parser is well suited for large XML documents. It
parses faster and consumes less memory
Example of event-based parsers:
XMLReader
XML Expat Parser
HANDLING XML
PHP has an excellent facilities for manipulating XML
By default this language includes the expat processor library
written by James Clark (This feature can be disabled during
the compilation of PHP)
Expat based processing is quite hard to work with
Its underlying library provides raw access to the XML document
Developers need to write functions which look for elements in the
XML document, extract and manipulate their attributes
PHP WITH DOM
Document Object Model (DOM) provides a uniform interface to XML
documents
DOM can be useful when you are creating XML documents in programs
as includes methods to create , add and validate documents
A DOM implementation is available in PHP5
PHP 4 has same facilities in an extension called as DOM XML
DOM extensions give access to an API which implements DOM Level 2
through the Object Oriented interfaces
Here the API is very low-level
Note:
Most programmers do not need all of the facilities of DOM implementation and
do not want to work at the level of a raw XML
They need a nice, clean interface which lets them to extract the information
from the XML documents
PHP 5 includes a extension called a SimpleXML to load and access the XML
documents
SIMPLE XML
SimpleXML is a PHP extension that allows us to easily
manipulate and get XML data.
simplexml_load_string(string)
If the parameter is a string which represents an XML document this
method returns an object of type SimpleXMLElement
The properties of the returned object have the name of the elements
from the XML and contain their data, attributes or children
In case the parameter string cannot be formatted as an object of the
SimpleXMLElement type , then the Boolean value false is returned
The contents of SimpleXMLElement object can be displayed using the
standard PHP var_dump() method
PHP SIMPLEXML - GET NODE VALUES
Get the node values from the “ data.xml" file:
Example
<?php
$xml=simplexml_load_file(“data.xml") or die("Error:
Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
BOOKS.XML
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
<?php
$xml=simplexml_load_file("books.xml") or die("Error:
Cannot create object");
echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>
OTHER FUNCTIONS
simplexml_import_dom(object)
If the script contains an XML document as a DOM object, this
method will load the properties of that object into a
SimpleXMLElement object
simplexml_load_file(URI)
Generally the XML data in the script is a sting or a DOM object
Sometimes we want to load a file which contains the XML at
runtime
The file may be available on the local filesystem or remotely via a
URL
This method encapsulates all of the functionality which is needed
to find and import the file and to create the SimpleXMLElement
object
If the loading or importing the data fails the method returns false
The underlying implementation uses the Libxml 2 library
SimpleXMLElement->asXML()
It takes the properties of the SimpleXMLElement object and
returns an XML document which contains them
SimpleXMLElement ->attributes()
Returns the attributes of the object if any, these can be iterated
across using a foreach loop
SimpleXMLElement->children()
Returns the children, if any, of the object so that they can be
iterated across
SimpleXMLElement->xpath(expression)
This method accepts an Xpath expression as its parameter
The element is evaluated against the expression
The result is returned as an array of SimpleXMLElement object
END of PHP