Unit 5
Unit 5
CHAPTER I
WORKING WITH DATABASES AND SQL
Features of PHP databases:
One of the reasons for PHP’s popularity as a Web scripting language is its support for a wide range
of relational database systems.
This support makes it easy for Web developers to create data-driven Web sites and to prototype new
Web applications quickly and efficiently, with minimal trouble and muss.
PHP supports more than fifteen different database engines, including Microsoft SQL Server, IBM
DB2, PostgreSQL, MySQL, and Oracle.
Until PHP5, this support was offered through native database extensions, each with its own
functions and features; however, this made it hard for developers to change from one database
engine to another.
PHP5 corrected this situation by introducing a common API for database access: the PHP Data
Objects (PDO) extension, which provides a unified interface to working with databases and helps
developers manipulate different databases in a consistent manner.
Introducing Databases and SQL
In the Internet age, information is no longer represented in filing cupboards instead; it’s stored as
digital ones and zeros in electronic data bases, which are data storage “containers” that impose a
certain structure on information.
In particular, most electronic data bases today are relational databases, which allow users to
definerelationshipsbetweendifferentdatabasetablesformoreeffectivesearchandanalysis.
There are a large number of database management systems currently available, some commercial
and some free.You’ve probably already heard of some of them: Oracle, Microsoft Access, My SQL,
and PostgreSQL.
These database systems are powerful, feature-rich software applications, capable of organizing and
searching millions of records at very high speeds; as such, they’re widely used by businesses and
government offices, often for mission-critical purposes.
1. Understanding Databases, Records, and Primar y Keys:
Every database is composed of one or more tables.These tables, which structure data into rows and columns,
impose organization on the data
The process of streamlining a database by defining and implementing one-to-one and one-to-many relationships
between its component tables is known as database normalization.
CREATEDATABASE library;
SELECT movie FROM movies WHERE rating>4;
DELETEFROM cars WHERE year_of_manufacture<1980;
In this section, you’ll use the interactive My SQL command-line client to create a database and
tables, add and edit records, and generate result sets matching various criteria.
Create a MySQL Table
The CREATE TABLE statement is used to create a table in My SQL.
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email"
and "reg_date":
Example:
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
After the data type, you can specify other optional attributes for each column:
NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT – My SQL automatically increases the value of the field by 1 each time a new
record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY
setting is often an ID number, and is often used with AUTO_INCREMENT
Insert Data Into My SQL
After a database and a table have been created, we can start adding data in them.
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
echo "EMP ID :{$row[0]} <br> ".
"EMP NAME : {$row[1]} <br> ".
"EMP SALARY : {$row[2]} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
ERROR HANDLING
The default error handling in PHP is very simple. An error message with filename, line number and a
message describing the error is sent to the browser.
PHP Error Handling
When creating scripts and web applications, error handling is an important part. If your code lacks
error checking code, your program may look very unprofessional and you may be open to security
risks.
Different error handling methods:
Simple "die()" statements
Custom errors and error triggers
Error reporting
1.Basic Error Handling: Using the die() function
//trigger error
echo($test);
?>
The output of the code above should be something like this:
Error: [8] Undefined variable: test
4.Trigger an Error
In a script where users can input data it is useful to trigger errors when an illegal input occurs. In
PHP, this is done by the trigger error () function.
Example
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>1) {
//trigger error
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Webmaster has been notified
And the mail received from the code above looks like this:
Error: [512] Value must be 1 or below
This should not be used with all errors. Regular errors should be logged on the server using the
default PHP logging system.
<?php
try {
$error = 'Always throw this error';
throw new Exception($error);
// Continue execution
echo 'Hello World';
?>
Here exception handler is the name of the function to be called when an uncaught exception
occurs. This function must be defined before calling set_exception_handler().
Example:
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
SQLITE EXTENSION
SQLite is an in-process library that implements a self-contained, server less, zero-configuration,
transactional SQL database engine.
It is the one database, which is zero-configured, that means like other database you do not need to
configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or
dynamically as per your requirement with your application. The SQLite accesses its storage files
directly.
Why SQLite?
SQLite does not require a separate server process or system to operate.(serverless).
Command Description
Command Description
Command Description
INT INTEGER
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
TEXT
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
BLOB
NONE
no datatype specified
REAL
DOUBLE
REAL
DOUBLE PRECISION
FLOAT
NUMERIC
DECIMAL(10,5)
BOOLEAN NUMERIC
DATE
DATETIME
Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers
0 (false) and 1 (true).
Date and Time Datatype:
$sqlite3 DatabaseName.db
$sqlite3 testDB.db
SQLite version 3.7.15.22013-01-0911:53:05
Enter".help"for instructions
Enter SQL statements terminated with a ";"
sqlite>
Example:
sqlite>.tables
COMPANY test.COMPANY
This means COMPANY table is available in the database, so let us drop it as follows:
If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not
need to use WHERE clause and UPDATE query would be as follows:
If you want to DELETE all the records from COMPANY table, you do not need to use WHERE
clause with DELETE query, which would be as follows:
Now, COMPANY table does not have any record because all the records have been deleted by
DELETE statement.
PDO EXTENSION
Assuming a successful connection, the next step is to formulate an SQL query and execute it using
PDO’s query () method.
The return value of this method is a result set, represented by a PDO Statement object.
The contents of the result set can be processed using the object’s fetch () method, which returns
the next record in the result set as an array (both associative and indexed).
Individual fields from the record can be accessed as array element s in a loop, using either the field
index or the fieldname.
The PDO Statement object’s fetch() method accepts an additional modifier, which controls how
result set records are fetched. Some valid values for this modifier are,
Modifier What It Does
PDO::FETCH_NUM Return search record as a numerically indexed array
PDO::FETCH_ASSO Return search record as an associative array keyed on the field
PDO::FETCH_BOTH
C Return
name search record as both a numerically indexed array and
an associative array (default value)
PDO::FETCH_OBJ Return search record as an object with properties
corresponding to the field names
PDO::FETCH_LAZY Return search record as a numerically indexed array, associative
array, and object
This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>...
</text>. The tags <message> and </message> mark the start and the end of the XML code fragment.
The tags <text> and </text> surround the text Hello, world!.
XML Technologies
As XML’s popularity has increased, so too has the list of technologies that use it. Here are a few that
you might have heard about already:
XML Schema XML Schemas define the structure and format of XML documents, allowing for
more flexible validation and support for data typing, inheritance, grouping, and database linkage.
XLink :XLink is a specification for linking XMLdata structures together. It allows for more
sophisticated link types than regular HTML hyperlinks, including links with multiple targets.
XPointer: XPointer is a specification for navigating the hierarchical tree structure of an
XMLdocument, easily finding elements, attributes, and other data structures within the document.
XSL The Extensible Stylesheet Language (XSL) applies formatting rules to XML documents and
“transforms” them from one format to another.
XHTML XHTMLcombines the precision of XMLmarkup with the easy-to- understand tags of
HTMLto create a newer, more standards-compliant version of HTML.
XFormsXForms separates the information gathered in aWeb form from the form’s appearance,
allowing for more stringent validation and easier reuse of forms in different media.
XML Query XMLQuery allows developers to query XML document and generate result sets, in
much the same way that SQLis used to query and retrieve database records.
XML Encryption and XML Signature XMLEncryption is a means of encrypting and decrypting
XMLdocuments, and representing the resulting data. It is closely related to XMLSignature, which
provides a way to represent and verify digital signatures with XML.
SVG ScalableVector Graphics (SVG) uses XMLto describe vector or raster graphical images, with
support for alpha masks, filters, paths, and transformations.
MathML Math MLuses XML to describe mathematical expressions and formulae, such that they
can be easily rendered by Web browsers.
SOAP The Simple Object Access Protocol (SOAP) uses XMLto encode requests and responses
between network hosts using HTTP.
Well-Formed and Valid XML
The XMLspecification makes an important distinction between well-formed and
valid documents.
To read an XML file with Simple XML, use the simplexml_load_file()function and
pass it the disk path to the target XML file.
This function will then read and parse the XML file and, assuming it is well-formed, return a
Simple XML object representing the document’s root element.
This object is only the top level of a hierarchical object tree that mirrors the internal structure of
the XML data: elements below the root element are represented as properties or child objects
and can thus be accessed using the standard parentObject->childObjectnotation.
Working with Attributes
If an XML element contains attributes, Simple XML has an easy way to get to these as well:
attributes and values are converted into keys and values of a PHP associative array and can be
accessed like regular array elements.
consider the following example, which reads the library.xml file from the preceding section and
prints each book title found, together with its 'genre'and'rating':
EXAMPLE:
<?php
//loadXML file
$xml =simplexml_load_file('library.xml') ordie("Unableto loadXML!");
//accessXML data
//for eachbook
//retrieve andprint'genre'and'rating'attributes
//output: 'TheShining\nGenre:horror\nRating:5 \n\n...' foreach($xml-
>bookas $book)
<?xml version='1.0'?>
<address>
<street>13 HighStreet</street>
<county>Oxfordshire</county>
<city>
<name>Oxford</name>
<zip>OX11BA</zip>
</city>
<country>UK</country>
</address>
Here’s a PHP script that uses the DOM extension to parse this file and retrieve the various
components of the address:
<?php
//initializenew DOMDocument
$doc= new DOMDocument();
//disable whitespace-onlytext nodes
$doc->preserveWhiteSpace= false;
//readXML file
$doc->load('address.xml');
//getroot element
$root= $doc->firstChild;
//gettext node'UK'
echo"Country:". $root->childNodes->item(3)->nodeValue."\n";
//gettext node'Oxford'
echo"City: ". $root->childNodes->item(2)->childNodes->
item(0)->nodeValue."\n";
//gettext node'OX1 1BA'
DOM relationships
Working with Attributes
The DOM also includes extensive support for attributes: every DOM Element object comes with a
UNIT V
2 MARKS