0% found this document useful (0 votes)
19 views30 pages

Unit - V-Wt-Php-Iib - Com (Ca)

Uploaded by

gansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views30 pages

Unit - V-Wt-Php-Iib - Com (Ca)

Uploaded by

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

SEMESTER III UNIT V

WEB TECHNOLOGY(PHP)

UNIT- V
Working with Database and SQL : Introducing Database and SQL- Using MySQL-Adding
and modifying Data-Handling Errors – Using SQLite Extension and PDO Extension.
Introduction XML - Simple XML and DOM Extension.

Introduction to Database
A database is a collection of interrelated data that helps in the efficient retrieval, insertion,
and deletion of data from the database and organizes the data in the form of tables, views,
schemas, reports, etc. For Example, a university database organizes the data about
students, faculty, admin staff, etc. which helps in the efficient retrieval, insertion, and
deletion of data from it.
A Database Management System (DBMS) is a software system that is designed to manage
and organize data in a structured manner. It allows users to create, modify, and query a
database, as well as manage the security and access controls for that database. DBMS
provides an environment to store and retrieve data in convenient and efficient manner.

Key Features of DBMS


 Data modeling: A DBMS provides tools for creating and modifying data models,
which define the structure and relationships of the data in a database.
 Data storage and retrieval: A DBMS is responsible for storing and retrieving data
from the database, and can provide various methods for searching and querying the
data.
 Concurrency control: A DBMS provides mechanisms for controlling concurrent
access to the database, to ensure that multiple users can access the data without
conflicting with each other.
 Data integrity and security: A DBMS provides tools for enforcing data integrity and
security constraints, such as constraints on the values of data and access controls that
restrict who can access the data.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 1


 Backup and recovery: A DBMS provides mechanisms for backing up and recovering
the data in the event of a system failure.
 DBMS can be classified into two types: Relational Database Management System
(RDBMS) and Non-Relational Database Management System (NoSQL or Non-SQL)
 RDBMS: Data is organized in the form of tables and each table has a set of rows and
columns. The data are related to each other through primary and foreign keys.
 NoSQL: Data is organized in the form of key-value pairs, documents, graphs, or
column-based. These are designed to handle large-scale, high-performance scenarios.
Data Definition Language (DDL)
DDL is the short name for Data Definition Language, which deals with database schemas
and descriptions, of how the data should reside in the database.
 CREATE: to create a database and its objects like (table, index, views, store procedure,
function, and triggers)
 ALTER: alters the structure of the existing database
 DROP: delete objects from the database
 TRUNCATE: remove all records from a table, including all spaces allocated for the
records are removed
 COMMENT: add comments to the data dictionary
 RENAME: rename an object
Data Manipulation Language (DML)
DML is the short name for Data Manipulation Language which deals with data
manipulation and includes most common SQL statements such SELECT, INSERT,
UPDATE, DELETE, etc., and it is used to store, modify, retrieve, delete and update data in
a database. Data query language(DQL) is the subset of “Data Manipulation Language”.
The most common command of DQL is SELECT statement. SELECT statement help on
retrieving the data from the table without changing anything in the table.
 SELECT: retrieve data from a database
 INSERT: insert data into a table
 UPDATE: updates existing data within a table
 DELETE: Delete all records from a database table
 MERGE: UPSERT operation (insert or update)
 CALL: call a PL/SQL or Java subprogram
 EXPLAIN PLAN: interpretation of the data access path
 LOCK TABLE: concurrency Control

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 2


SQL

History of SQL

SQL was invented in the 1970s based on the relational data model. It was initially known as
the structured English query language (SEQUEL). The term was later shortened to SQL.
Oracle, formerly known as Relational Software, became the first vendor to offer a
commercial SQL relational database management system.

Structured query language (SQL) is a programming language for storing and processing
information in a relational database. A relational database stores information in tabular form,
with rows and columns representing different data attributes and the various relationships
between the data values. You can use SQL statements to store, update, remove, search, and
retrieve information from the database. You can also use SQL to maintain and optimize
database performance.
Importance of SQL
Structured query language (SQL) is a popular query language that is frequently used in all
types of applications. Data analysts and developers learn and use SQL because it integrates
well with different programming languages. For example, they can embed SQL queries with
the Java programming language to build high-performing data processing applications with
major SQL database systems such as Oracle or MS SQL Server. SQL is also fairly easy to
learn as it uses common English keywords in its statements

OVERVIEW OF THE SQL QUERY :


o SQL stands for Structured Query Language. It is used for storing and managing data
in relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create,
read, update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL
as their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.

SQL follows the following rules:

o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text line.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 3


o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.

SQL process:

o When an SQL command is executing for any RDBMS, then the system figure out the
best way to carry out the request and the SQL engine determines that how to interpret
the task.
o In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query
engine won't handle logical files.

The DDL Languages or commands are categorized into five commands which are widely
used in the SQL queries:

1. CREATE DDL Command


2. ALTER DDL Command
3. DROP DDL Command
4. TRUNCATE DDL Command
5. RENAME DDL Command

Let's discuss each DDL command with syntax and examples.

CREATE Command :This DDL command allows us to create the new table, function,
stored procedure, and other database objects.

Syntax of Create DDL Command to create a new table in the database:

CREATE TABLE Name_of_Table ( Column1 datatype (Length), Column2 datatype (Length


) …….);

Example of Create Command:

The following SQL query creates the new Mobile_Details table using CREATE DDL
command:

CREATE TABLE Mobile_Details(Mobile_Number INT NOT NULL, Mobile_Name Varch


ar(50), Manufacturing_Year INT NOT NULL, Mobile_Cost INT);

ALTER Command : This DDL command allows us to modify the structure of database
objects.

Syntax of Alter Command to modify the existing table:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 4


ALTER TABLE Name_of_Table ADD Column_Name Datatype (Length of Column);

Example of Alter Command:

The following SQL query adds the new column in the Mobile_Details table using ALTER
DDL command:

ALTER TABLE Mobile_Details ADD Mobile_Color Varchar (50);

DROP Command : This DDL command allows us to remove the table definition and
data from the SQL systems.

Syntax of Drop Command to remove the existing table:

1. DROP TABLE Name_of_Table;

Example of Drop Command:

The following SQL query deletes the Mobile_Details table using the DROP DDL command:

DROP TABLE Mobile_Details;

TRUNCATE Command : This DDL command allows the database users to remove all
the existing records from the table.

Syntax of Truncate Command to delete all records:

TRUNCATE TABLE Name_of_Table;

Example of Truncate Command:

The following SQL query deletes all the inserted records from the Mobile_Details table using
the TRUNCATE DDL command:

TRUNCATE TABLE Mobile_Details;

RENAME Command : This DDL command allows the users to change the name of the
existing table.

Syntax of RENAME Command for changing the table name:

RENAME Old_Table_Name TO New_Table_Name;

Example of Rename Command:

The following SQL query changes the name of Mobile_Details table to Mobile_Records table
using the RENAME DDL command:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 5


RENAME Mobile_Details TO Mobile_Records;

DML (Data Manipulation Language)

Data Manipulation languages allow database users to change the existing data of the tables.

We can use this type of language when we want to access the record, insert the new record,
update the record, and delete the existing values from the tables.

Following are the four DML Languages or commands used in the SQL queries:

1. SELECT DML Command


2. INSERT DML Command
3. UPDATE DML Command
4. DELETE DML Command

Let's discuss each DML command with syntax and examples.

SELECT Command :This DML command allows us to access the stored records from the
tables. We can also use the condition in the SELECT command for accessing the
particular rows.

Syntax of SELECT Command: SELECT * FROM Name_of_Table;

Example of SELECT Command:

The following SQL query shows the records of the Mobile_Records table using the SELECT
DML command:

SELECT * FROM Mobile_Records;

INSERT Command :This DML command allows the database users to insert the new
record or rows in the tables.

Syntax of INSERT Command for inserting the single record:


INSERT INTO Name_of_Table ( Column_1, Column_2, Column_3, …..) VALUES (Value1
_of_Column_1, Value2_of_Column_2, Value3_of_Column_3,…….);

Example of INSERT Command:

The following SQL query inserts the single record of mobile into the Mobile_Records table
using the INSERT DML command:

INSERT INTO Mobile_Records (Mobile_number, Mobile_Name, Manufacturing_Year, Mo


bile_Cost, Mobile_Color) VALUES (95872, Apple, 2020, 95000, Black);

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 6


UPDATE Command :This DML command allows the database users to change the
existing record or rows in the tables.

Syntax of UPDATE Command for modifying the records:


UPDATE Name_of_Table SET Column_Name = Value WHERE [ Condition ];

Example of UPDATE Command:

The following SQL query updates the values of the Mobile_Records table using the
UPDATE DML command:

UPDATE Mobile_Records SET Manufacturing_Year = 2022 WHERE Mobile_Color = 'Whit


e';

DELETE Command : This DML command allows the database users to delete a
particular record or row from the tables.

Syntax of DELETE Command for removing the records:

DELETE FROM Name_of_Table WHERE [ condition ];

Example of DML DELETE Command:

The following SQL query deletes the values from the Mobile_Records table using the
DELETE DML command:

o DELETE FROM Mobile_Records WHERE Manufacturing_Year = 2019;

MySQL

 MySQL is a database system used on the web


 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
The data in a MySQL database are stored in tables. A table is a collection of related data, and
it consists of columns and rows.
Databases are useful for storing information categorically. A company may have a database
with the following tables:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 7


 Employees
 Products
 Customers
 Orders
PHP + MySQL Database System
 PHP combined with MySQL are cross-platform (you can develop in Windows and
serve on a Unix platform)

Database Queries

A query is a question or a request.


We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the "Employees" table.

Create a MySQL

The CREATE TABLE statement is used to create a table in MySQL.


We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":

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 DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)
The data type specifies what type of data the column can hold. For a complete reference of all
the available data types, go to our Data Types reference.
After the data type, you can specify other optional attributes for each column:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 8


 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 - MySQL 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

Each table should have a primary key column (in this case: the "id" column). Its value must
be unique for each record in the table.
The following examples shows how to create the table in PHP:
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 DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

Insert Data

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 9


INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

SQL ADD and ALTER TABLE


SQL ALTER TABLE command can add, delete, or modify columns of an existing table.
This article discusses the SQL ALTER TABLE statement with examples and syntax.

ALTER TABLE STATEMENT


The ALTER TABLE statement in SQL is used to add, remove, or modify columns in an
existing table. The ALTER TABLE statement is also used to add and remove various
constraints on existing tables.
It allows for structural changes like adding new columns, modifying existing ones, deleting
columns, and renaming columns within a table.

Syntax
To alter/modify the table use the ALTER TABLE syntax:
ALTER TABLE table_name
clause [column_name] [datatype];

Here, the clause is the operational clause of the ALTER TABLE statement. Some key
clauses of the ALTER TABLE statement are:

ADD – To add a new column to the table:


ALTER TABLE table_name
ADD column_name datatype;

MODIFY/ALTER – To change the data type of an existing column:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 10


DROP – To delete an existing column from the table:

ALTER TABLE table_name


DROP COLUMN column_name;

RENAME COLUMN – To rename an existing column:

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

RENAME TO – To rename the table itself:

ALTER TABLE table_name


RENAME TO new_table_name;

SQL ALTER TABLE Examples

Below are the examples of ALTER TABLE statement. These examples demonstrates
different use cases and shows how to use ALTER TABLE statement in SQL.

SQL ALTER TABLE ADD Column Example

The following SQL query adds an “Email” column to the “Students” table:
ALTER TABLE Students
ADD Email varchar(255);

SQL ALTER TABLE DROP Column Example

The following query deletes the “Email” column from “Students” table:
ALTER TABLE Students
DROP COLUMN Email;

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 11


SQL ALTER TABLE MODIFY Column Example

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

SQL ALTER TABLE Queries


Suppose there is a student database:

ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

To ADD 2 columns AGE and COURSE to table Student.


Query:
ALTER TABLE Student ADD
(AGE number(3),COURSE varchar(40));
Output:

ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 12


MODIFY column COURSE in table Student.
Query:
ALTER TABLE Student
MODIFY COURSE varchar(20);
After running the above query the maximum size of the Course Column is reduced to 20
from 40.
DROP column COURSE in table Student.

Query:
ALTER TABLE Student
DROP COLUMN COURSE;
Output:

ROLL_NO NAME AGE

1 Ram

2 Abhi

3 Rahul

4 Tanu

Handling errors in SQL


An exception is an error which disrupts the normal flow of program instructions. PL/SQL
provides us the exception block which raises the exception thus helping the programmer to
find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL
1. User defined exception.
2. System defined exceptions.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 13


Syntax to write an exception
WHEN exception THEN
statement;

DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;

1.User defined exceptions:


This type of users can create their own exceptions according to the need and to raise these
exceptions explicitly raise command is used.
Example:
 Divide non-negative integer x by y such that the result is greater than or equal to 1.
From the given question we can conclude that there exist two exceptions
o Division be zero.
o If result is greater than or equal to 1 means y is less than or equal to x.

RAISE_APPLICATION_ERROR :
It is used to display user-defined error messages with error number whose range is in
between -20000 and -20999. When RAISE_APPLICATION_ERROR executes it returns
error message and error code which looks same as Oracle built-in error.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 14


Scope rules in exception handling :
1. We can’t DECLARE an exception twice but we can DECLARE the same exception
in two dIFferent blocks.
2. Exceptions DECLAREd inside a block are local to that block and global to all its sub-
blocks.

2.System defined exceptions:


These exceptions are predefined in PL/SQL which get raised WHEN certain database rule
is violated.
System-defined exceptions are further divided into two categories:
1. Named system exceptions.
2. Unnamed system exceptions.

Named system exceptions: They have a predefined name by the system like
ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the list is quite
big.
1.NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows.
2.TOO_MANY_ROWS:It is raised WHEN a SELECT INTO statement returns more than
one row.
3.VALUE_ERROR:This error is raised WHEN a statement is executed that resulted in an
arithmetic, numeric, string, conversion, or constraint error. This error mainly results from
programmer error or invalid data input.
4. ZERO_DIVIDE = raises exception WHEN dividing with zero.

Unnamed system exceptions :


Oracle doesn’t provide name for some system exceptions called unnamed system
exceptions.These exceptions don’t occur frequently.These exceptions have two parts code
and an associated message.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 15


Introduction to XML

What is XML?

 XML stands for eXtensible Markup Language


 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation

The XML above is quite self-descriptive:

 It has sender information


 It has receiver information
 It has a heading
 It has a message body

Extensible Markup Language (XML) is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. The
design goals of XML focus on simplicity, generality, and usability across the Internet. It is
a textual data format with strong support via Unicode for different human languages.
Although the design of XML focuses on documents, the language is widely used for the
representation of arbitrary data structures such as those used in web services.

1. XML stands for extensible Markup Language


2. XML is a markup language like HTML
3. XML is designed to store and transport data
4. XML is designed to be self-descriptive

Differences between XML and HTML


XML and HTML were designed with different goals:

 XML is designed to carry data emphasizing on what type of data it is.


 HTML is designed to display data emphasizing on how data looks

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 16


 XML tags are not predefined like HTML tags.
 HTML is a markup language whereas XML provides a framework for defining markup
languages.
 HTML is about displaying data,hence it is static whereas XML is about carrying
information,which makes it dynamic.
EXAMPLE :
XML code for a note is given below

HTML code for the note is given below


<!DOCTYPE html>
<html>
<h1>Note</h1>
<body>
<p>To:RAJ
<br>
From:RAVI
</p>
<h1>Reminder</h1>
<p>Meeting at 8am</p>
</body>
</html>

OUTPUT:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 17


Another Example:
The XML above is quite self-descriptive:
 It has sender information.
 It has receiver information.
 It has a heading.
 It has a message body.
 The tags in the example below are not defined in any XML standard. These tags are
“invented” by the author of the XML document.HTML works with predefined tags like
p tag, h1 tag, etc.While in XML, the author must define both the tags and the document
structure.
Input:

Output:
Basically XML above does not do anything. XML is just information wrapped in tags.
Users must require a piece of software to send, receive, store, or display it.

XML makes web development User Friendly : Many computer systems contain data in
incompatible formats. Exchanging data between incompatible systems or upgraded systems
is a time-consuming task for web developers. Large amounts of data must be converted,
and incompatible data is often lost. XML stores data in plain text format. This provides a
software- and hardware-independent way of storing, transporting, and sharing data.
XML is Extensible: XML applications will work as expected even if data is edited i.e.
added or removed.
Example :The above note is edited into a newer version by adding date tag and hour tag ,
and by removing the heading tag.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 18


Previous version

New Version
output:
Note
To:Raj
From:Ravi
Date:2015-09-01 08:30
Meeting at 8am

What is SQLite
SQLite is a software library that provides a relational database management system. The
lite in SQLite means lightweight in terms of setup, database administration, and required
resources.

SQLite has the following noticeable features:

 Self-contained
 Serverless
 Zero-configuration
 Transactional

Serverless

An RDBMS such as MySQL, PostgreSQL, etc., normally requires a separate server process
to run. The applications that want to access the database server use TCP/IP protocol to send
and receive requests. This is called client/server architecture.

The following diagram illustrates the RDBMS client/server architecture:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 19


SQLite does NOT work this way.

SQLite does NOT require a server to run.

SQLite database is integrated with the application that accesses the database. The
applications interact with the SQLite database reading and writing directly from the database
files stored on disk.

The following diagram illustrates the SQLite server-less architecture:

Self-Contained

SQLite is self-contained, which means it requires minimal support from the operating system
or external library. This makes SQLite usable in any environment, especially in embedded
devices like iPhones, Android phones, game consoles, handheld media players, etc.

SQLite is developed using ANSI-C. The source code is available as a big sqlite3.c and its
header file sqlite3.h. If you want to develop an application that uses SQLite, you drop these
files into your project and compile them with your code.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 20


Zero-configuration

Because of the serverless architecture, you don’t need to “install” SQLite before using it. No
server process needs to be configured, started, and stopped.

In addition, SQLite does not use any configuration files.

Transactional

All transactions in SQLite are fully ACID-compliant, which means all queries and changes
are Atomic, Consistent, Isolated, and Durable.

In other words, all changes within a transaction take place completely or not at all even when
an unexpected situation like an application crash, power failure, or operating system crash
occurs.

SQLite distinctive features

SQLite uses dynamic types for tables. It means you can store any value in any column,
regardless of the data type.

SQLite allows a single database connection to access multiple database files simultaneously.
This brings many nice features like joining tables in different databases or copying data
between databases in a single command.

SQLite is capable of creating in-memory databases that are very fast to work with.

Introduction to PHP PDO


PHP is an open-source general-purpose scripting language, which is widely used for
creating dynamic and interactive web pages. PHP can access a large range of relational
database management systems such as MYSQL, SQLite, and PostgreSQL. The PHP
5.1 version offered a new database connection abstraction library, which is PHP Data
Objects (PDO).

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 21


What is PDO?

PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and
consistent interface for accessing a database in PHP. It is a set of PHP extensions which
provide a core PDO class and database-specific driver. Each database driver can expose
database-specific features as a regular extension function that implements the PDO interface.

PDO mainly focuses on data access abstraction rather than database abstraction. It
provides data-access abstraction layer, which means, regardless of which database we are
using, we have to use the same functions provided by that database to issue queries and fetch
data. PDO does not provide data abstraction, as it does not rewrite the SQL or emulate
missing features.

Advantage of PDO

PDO provides various ways to work with objects and retrieves prepared statements that make
work much easier. It is a database access tool in PHP through which we enable uniform
access across several databases.

PDO allows comparatively seamless switching between different databases and platforms,
which can be easily done by changing the connection string. It does not support database-
specific syntaxes.

There are some advantages of PDO as follows:

o Database support
The PDO extension can access any database which is written for PDO driver. There
are several PDO drivers available which are used for FreeTDS, Microsoft SQL
Server, Sybase, IBM DB2, Oracle Call Interface, Firebird/Interbase 6,
and PostgreSQL databases, among many more.
The drivers are not available in every system automatically, so we have to find our
available drivers and add ones when we need them.
o Database connecting
There are different syntaxes available to establish the database connection. These
syntaxes depend on specific databases. While using PDO, operations must be
wrapped in try/catch blocks and utilize the exception technique.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 22


Usually, only a single connection needs to create, and these connections are closed by
programming the database to set as a null.
o Error handling
PDO permits to use exceptions for error handling. To produce an exception, PDO can
be forced into a relevant error mode attribute.
There are three error modes, i.e., Silent (default), Warning, and Exception. Warning
and Exception are more useful in DRY programming.

o Silent - It is a default error mode.


o Warning - It is useful for debugging.
o Exception - This mode allows graceful error handling while hiding data that a
person might use to exploit your system.

o Insert and Update


PDO reduces the commonly used insert and update database operation into a two-step
process, i.e.
Prepare >> [Bind] >> Execute.
Through this method, we can take full advantage of PDO's prepared statements,
which protect against malicious attacks through SQL injection.
Prepared statements are pre-compiled SQL statements that can be executed multiple
times by sending this data to the server. This data, which is used within the
placeholder, is automatically protected from the SQL injection attack.

Benefits of using PDO

PDO is the native database driver. There are some benefits of using PDO that are given
below:

o Usability - It contains many helper functions to operate automatic routine operations.


o Reusability - It offers the unified API to access multiple databases.
o Security - It uses a prepared statement which protects from SQL injection. A
prepared statement is a pre-compiled SQL statement that separates the instruction of
the SQL statement from the data.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 23


PDO Classes

There are three PDO classes, which are given below:

o PDO - It represents a connection between PHP and the database.


o PDOStatement - It represents the prepared statement and after the execution of the
statement, sets an associated result.
o PDOException - It represents errors raised by PDO.

o $conn = new PDO($db_name,$username,$password);

XML | Syntax

XML syntax rule which is used while writing an XML document or an XML
application. It is a very simple and straight forward to learn and code. Below is a
complete XML document to discuss each component in detail.

What is XML?

 XML stands for eXtensible Markup Language


 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive

XML Syntax Rules


XML Documents Must Have a Root Element

XML documents must contain one root element that is the parent of all other elements:

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

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


<note>
<to>Tove</to>
<from>Jani</from>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 24


<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML Prolog

This line is called the XML prolog:

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

The XML prolog is optional. If it exists, it must come first in the document.

XML documents can contain international characters, like Norwegian øæå or French êèé.

To avoid errors, you should specify the encoding used, or save your XML files as UTF-8.

UTF-8 is the default character encoding for XML documents.

All XML Elements Must Have a Closing Tag

In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph.</p>
<br />

XML Tags are Case Sensitive

XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.

Opening and closing tags must be written with the same case:

<message>This is correct</message>
Opening and closing tags" are often referred to as "Start and end tags". Use whatever you
prefer. It is exactly the same thing.

Comments in XML

The syntax for writing comments in XML is similar to that of HTML:

<!-- This is a comment -->

In this example <note> is the root element:


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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 25


<to>Students</to>
<from>Teacher</from>
<subject>Regarding assignment submission</subject>
<text>All students will have to submit assignment by tomorrow.</text>
</message>

Syntax rules for XML declaration or XML Prolog:

 XML

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

Below is the explanation of each point.

 This line is called XML Prolog or XML declaration.


 This line is optional i.e, it can be either used or not in an XML document. However, it
should be the very first line if used.
 The version=”1.0″ is the version of the XML currently used. There are various versions
of XML available.
 The encoding=”UTF-8″ specifies the character encoding used while writing an XML
document, for example, êèé is for French and so on. Its default value is “UTF-8”. For
more about character encoding
 This declaration is case sensitive for example “xml” should be in lower case in .
Syntax rules for Root Element:
 Every XML files should have one or more Root elements to avoid error. For example
below code is wrong because it’s not containing Root element.

 XML

<to>Students</to>
<from>Teacher</from>
<subject>Regarding assignment submission</subject>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 26


<text>All students will have to submit assignment by tomorrow.</text>

 In the first example the Root element is <message> and all the remaining elements
<to>, <from> etc is the child element and reside within the root element.
 It is case sensitive.
 The XML element should have a closing element for example <text category =
“message”>Hi</text> is correct but <text category = “message”>Hi is not correct
because it does not contain the closing element and it will throw an error and vice-
versa.
 The elements in XML should be nested properly otherwise it will throw an error. For
example <to><from>Geeks</from></to> is nested correctly
but <to><from>Geeks</to></from> is wrong because if <from> is opened inside the
<to> element then this should also end inside of the </to> element.
 It is also case sensitive i.e, the starting and closing element should be in the same case.
For example <to>….</to> is correct but <to>…..</To> is not correct and it will throw
an error.
 The XML attribute is having two part one is Name and other is its value. It resides
inside of the opening of an XML element. For example: <text category =
“message”>All students will have to submit the assignment by tomorrow.</text> Here
category is the attribute name and message is its value and the attribute value should
either be in a single quotation or in double quotation otherwise it will throw an error.
The Attribute Name is written without any quotation.
 The XML attribute is also case sensitive.
 An XML element can have multiple attributes but can not have the same attribute
names in the same element. For example: <text category =”message” purpose =
“greet”>GeeksforGeeks</text> Above attributes is correct because of having multiple
attributes with the different attribute name. <text category =”message” category =
“greet”>GeeksforGeeks</text> Above attribute is wrong because of having the same
attribute name in a single element.
XML Comments: Correct syntax for writing XML comments are: <!– It is comment
section –>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 27


Incorrect comments: <!– It is comment — section –> i.e. Two dashes in between the
comment is not allowed.

DOM

The Document Object Model (DOM) defines a standard for accessing and manipulating
documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."

The HTML DOM defines a standard way for accessing and manipulating HTML documents.
It presents an HTML document as a tree-structure.

The XML DOM defines a standard way for accessing and manipulating XML documents. It
presents an XML document as a tree-structure.

The DOM extension allows operations on XML and HTML documents through the DOM
API with PHP.

The HTML DOM

All HTML elements can be accessed through the HTML DOM.


This example changes the value of an HTML element with id="demo":

<!DOCTYPE html>
<html>
<body>

<h1 id="demo">This is a Heading</h1>

<button type="button"
onclick="document.getElementById('demo').innerHTML = 'Hello World!'">Click
Me!

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 28


</button>

</body>
</html>

OUTPUT

This is a Heading

The XML DOM

All XML elements can be accessed through the XML DOM.

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>

This code retrieves the text value of the first <title> element in an XML document:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 29


Example

txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 30

You might also like