0% found this document useful (0 votes)
76 views

Unit 5

1. The document discusses features of PHP for working with databases including support for 15+ database engines through PDO and how this makes PHP popular for creating data-driven websites. 2. It introduces databases and SQL, explaining that databases store information digitally in tables, and relational databases define relationships between tables. 3. The main SQL statements - DDL, DML, DCL - are defined along with examples of creating databases and tables, inserting and selecting data, and deleting records in MySQL.

Uploaded by

Selvam Mano
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)
76 views

Unit 5

1. The document discusses features of PHP for working with databases including support for 15+ database engines through PDO and how this makes PHP popular for creating data-driven websites. 2. It introduces databases and SQL, explaining that databases store information digitally in tables, and relational databases define relationships between tables. 3. The main SQL statements - DDL, DML, DCL - are defined along with examples of creating databases and tables, inserting and selecting data, and deleting records in MySQL.

Uploaded by

Selvam Mano
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

UNIT: V

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

ID Year Location Sales ($)

Department of Computer Science Page 1


1 2007 Dallas 9495
2 2007 Chicago 8574
3 2007 Washington 12929
4 2007 New York 13636
5 2007 Los 8748
Angeles
6 2007 Boston 3478
7 2008 Dallas 15249
An example table
Primary key:
 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Primary keys must contain unique values.
 A primary key column cannot contain NULL values.
 Most tables should have a primary key, and each table can have only ONE primary key.
 The primary key of a relational table uniquely identifies each record in the table.
Record:
 A record is a database entry that may contain one or more values. Groups of records are stored in
a table, which defines what types of data each record may contain. Databases may contain multiple
tables which may each contain multiple records.
Database:
 A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view, databases can be classified according to types of content:
bibliographic, full-text, numeric, and images.
2. Understanding Relationships and Foreign Keys
 You already know that a single database can hold multiple tables. In a relational database system,
these tables can be linked to each other by one or more common fields, called foreign keys.
 These foreign keys make it possible to create one-to-one or one-to-many relationships between
different tables, and combine data from multiple tables to create more comprehensive result sets.

Department of Computer Science Page 2


Normalization:

 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.

3. Understanding SQL Statements


 Structured Query Language, or SQL, is the standard language used to communicate with a database,
add or change records and user privileges, and perform queries.
 The language, which became an ANSI standard in 1989, is currently used by almost all of today’s
commercial RDBMSs.
SQL statements fall into one of three categories:
 Data Definition Language (DDL) DDL consists of statements that define the structure and
relationships of a database and its tables. Typically, these statements are used to create, delete, and
modify databases and tables; specify field names and types; and set indexes.
 Data Manipulation Language (DML) DML statements are related to altering and extracting
data from a database. These statements are used to add records to, and delete records from, a
database; perform queries; retrieve table records matching one or more user-specified criteria; and
join tables together using their common fields.
 Data Control Language (DCL) DCL statements are used to define access levels and security
privileges for a database. You would use these statements to grant or deny user privileges; assign
roles; change passwords; view permissions; and create rule sets to protect access to data.
 SQL commands resemble spoken English, which makes the language easy to learn. The syntax is
quite intuitive as well: every SQL statement begins with an “action word,” like DELETE,
INSERT,ALTER, or DESCRIBE, and ends with a semicolon.
 Whitespace, tabs, and carriage returns are ignored. Here are a few examples of valid SQL
statements:

CREATEDATABASE library;
SELECT movie FROM movies WHERE rating>4;
DELETEFROM cars WHERE year_of_manufacture<1980;

lists the syntax for some common SQLstatements, with explanations.

Department of Computer Science Page 3


USING MY SQL

 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.

Department of Computer Science Page 4


 Here are some syntax rules to follow:
 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:
Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
Select Data from a MySQL Database
 The SELECT statement is used to select data from one or more tables
Syntax:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL records from a table:
SELECT * FROM table_name
Example:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
Delete Data From a MySQL Table
 The DELETE statement is used to delete records from a table.
Syntax:
DELETE FROM table_name
WHERE some_column = some_value
Example:
$sql = "DELETE FROM MyGuests WHERE id=3";
Guest Table:
id firstname Lastname email reg_date
1 John Doe [email protected] 2014-10-22
14:26:15
2 Mary Moe [email protected] 2014-10-23
10:22:30
3 Julie Dooley [email protected] 2014-10-26
10:48:23

Department of Computer Science Page 5


After delete
id firstname lastname email reg_date
1 John Doe [email protected] 2014-10-22
14:26:15
2 Mary Moe [email protected] 2014-10-23
10:22:30

Update Data In a MySQL Table


 The UPDATE statement is used to update existing records in a table,
Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value 
Example:
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
MyGuest Table:
id firstname lastname email reg_date
1 John Doe [email protected] 2014-10-22
14:26:15
2 Mary Moe [email protected] 2014-10-23
10:22:30

Getting Data From MySQL Database


 Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. You have several options to fetch data from MySQL.
 The most frequently used option is to use function mysql_fetch_array(). This function returns row
as an associative array, a numeric array, or both. This function returns FALSE if there are no more
rows.
 Below is a simple example to fetch records from employee table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

Department of Computer Science Page 6


if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

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

Department of Computer Science Page 7


 The first example shows a simple script that opens a text file:
<?php
$file=fopen("welcome.txt","r");
?>
 If the file does not exist you might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2
 To prevent the user from getting an error message like the one above, we test whether the file exist
before we try to access it:
Example:
<?php
if(!file_exists("welcome.txt")) {
  die("File not found");
} else {
  $file=fopen("welcome.txt","r");
}
?>
 Now if the file does not exist you get an error like this:
File not found

2.Creating a Custom Error Handler


 Creating a custom error handler is quite simple. We simply create a special function that can be
called when an error occurs in PHP.
 This function must be able to handle a minimum of two parameters (error level and error message)
but can accept up to five parameters (optionally: file, line-number, and the error context):
Syntax:
error_function(error_level,error_message,
error_file,error_line,error_context)

Error Report levels


Parameter Description
error_level Required. Specifies the error report level for the user-defined error. Must be a value
number. See table below for possible error report levels
error_message Required. Specifies the error message for the user-defined error

Department of Computer Science Page 8


error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their values, in use when
the error occurred
These error report levels are the different types of error the user-defined error handler can be used
for:
Valu Constant Description
e
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an
error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the
programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an
E_WARNING set by the programmer using the PHP function
trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the
programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be
caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL
in PHP 5.4)
 Now lets create a function to handle errors:
Function custom Error($errno, $errstr)
{
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
}
 The code above is a simple error handling function. When it is triggered, it gets the error level and an
error message.
 It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.
3.Set Error Handler

Department of Computer Science Page 9


 The default error handler for PHP is the built in error handler. We are going to make the function
above the default error handler for the duration of the script.
 It is possible to change the error handler to apply for only some errors, that way the script can handle
different errors in different ways.
 However, in this example we are going to use our custom error handler for all errors:
set_error_handler("customError");
 Since we want our custom function to handle all errors, the set_error_handler() only needed one
parameter, a second parameter could be added to specify an error level.
Example
 Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
functioncustomError($errno, $errstr)
{
  echo "<b>Error:</b> [$errno] $errstr";
}

//set error handler


set_error_handler("customError");

//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) {

Department of Computer Science Page 10


  trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6
 An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can
specify what error level is triggered.
Possible error types:
 E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from.
Execution of the script is halted
 E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not
halted
 E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might
be an error, but could also happen when running a script normally
Example
 In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an
E_USER_WARNING occurs we will use our custom error handler and end the script:
<?php
//error handler function
functioncustomError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//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:

Department of Computer Science Page 11


Error: [512] Value must be 1 or below
Ending Script
5.Error Logging
 By default, PHP sends an error log to the server's logging system or a file, depending on how the
error_log configuration is set in the php.ini file.
 By using the error_log() function you can send error logs to a specified file or a remote destination.
 Sending error messages to yourself by e-mail can be a good way of getting notified of specific errors.
6.Send an Error Message by E-Mail
 In the example below we will send an e-mail with an error message and end the script, if a specific
error occurs:
<?php
//error handler function
functioncustomError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Webmaster has been notified";
  error_log("Error: [$errno] $errstr",1,
  "[email protected]","From: [email protected]");
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//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.

Department of Computer Science Page 12


Exceptions Handling:
 PHP 5 has an exception model similar to that of other programming languages. An exception are
important and provides a better control over error handling.
 Three new keyword related to exceptions.
 Try - A function using an exception should be in a "try" block. If the exception does not trigger, the
code will continue as normal. However if the exception triggers, an exception is "thrown".
 Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".
 Catch - - A "catch" block retrieves an exception and creates an object containing the exception
information.
 When an exception is thrown, code following the statement will not be executed, and PHP will
attempt to find the first matching catch block.
 If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ...
 An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try
block.
 Each try must have at least one corresponding catch block. Multiple catch blocks can be used to
catch different classes of exceptions.
 Exceptions can be thrown (or re-thrown) within a catch block.
Example:
Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
try {
$error = 'Always throw this error';
throw new Exception($error);

// Code following an exception is not executed.


echo 'Never executed';

} catch (Exception $e) {


echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

 In the above example $e->getMessage function is uded to get error message.

Department of Computer Science Page 13


 There are following functions which can be used from Exception class.
 getMessage()- message of exception
 getCode() - code of exception
 getFile() - source filename
 getLine() - source line
 getTrace() - n array of the backtrace()
 getTraceAsString() - formated string of trace

Creating Custom Exception Handler:


 You can define your own custom exception handler. Use following function to set a user-defined
exception handler function.

string set_exception_handler ( callback $exception_handler )

 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).

Department of Computer Science Page 14


 SQLite comes with zero-configuration, which means no setup or administration needed.
 A complete SQLite database is stored in a single cross-platform disk file.
 SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with
optional features omitted.
 SQLite is self-contained, which means no external dependencies.
 SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
 SQLite supports most of the query language features found in the SQL92 (SQL2) standard.
 SQLite is written in ANSI-C and provides simple and easy-to-use API.
SQLite Commands:
 The standard SQLite commands to interact with relational databases are similar as SQL.
 They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.
 These commands can be classified into groups based on their operational nature:
DDL - Data Definition Language:

Command Description

CREATE Creates a new table, a view of a table, or other object in database

ALTER Modifies an existing database object, such as a table.

Deletes an entire table, a view of a table or other object in the


DROP
database.

DML - Data Manipulation Language:

Command Description

INSERT Creates a record

UPDATE Modifies records

DELETE Deletes records

DQL - Data Query Language:

Command Description

SELECT Retrieves certain records from one or more tables

SQLite Affinity and Type Names:


 Following table lists down various data type names which can be used while creating SQLite3 tables
and corresponding applied affinity also has been shown:

Data Type Affinity

INT INTEGER

Department of Computer Science Page 15


INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8

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:

Department of Computer Science Page 16


 SQLite does not have a separate storage class for storing dates and/or times, but SQLite is capable of
storing dates and times as TEXT, REAL or INTEGER values.

Storage Class Date Formate

TEXT A date in a format like "YYYY-MM-DD HH:MM:SS.SSS".

The number of days since noon in Greenwich on November 24,


REAL
4714 B.C.

INTEGER The number of seconds since 1970-01-01 00:00:00 UTC.

SQLite - CREATE Database


 The SQLite sqlite3 command is used to create new SQLite database. You do not need to have any
special privilege to create a database.
Syntax:
 Basic syntax of sqlite3 command is as follows:

$sqlite3 DatabaseName.db

Always, database name should be unique within the RDBMS.


Example:
 If you want to create new database <testDB.db>, then SQLITE3 statement would be as follows:

$sqlite3 testDB.db
SQLite version 3.7.15.22013-01-0911:53:05
Enter".help"for instructions
Enter SQL statements terminated with a ";"
sqlite>

 Above command will create a file testDB.db in the current directory.


 This file will be used as database by SQLite engine.
 If you have noticed while creating database, sqlite3 command will provide a sqlite>prompt after
creating database file successfully.
SQLite - INSERT Query
 The SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.
Syntax:
 There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


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

Department of Computer Science Page 17


 Here, column1, column2,...columnN are the names of the columns in the table into which you want
to insert data.
Example:
 Consider you already have created COMPANY table in your testDB.db as follows:

sqlite> CREATE TABLE COMPANY(


ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);

SQLite - DROP Table


 The SQLite DROP TABLE statement is used to remove a table definition and all associated data,
indexes, triggers, constraints and permission specifications for that table.
Syntax:
 Basic syntax of DROP TABLE statement is as follows. You can optionally specify database name
along with table name as follows:

DROP TABLE database_name.table_name;

Example:

sqlite>.tables
COMPANY test.COMPANY

 This means COMPANY table is available in the database, so let us drop it as follows:

sqlite>DROP TABLE COMPANY;


sqlite>

SQLite - UPDATE Query


 The SQLite UPDATE Query is used to modify the existing records in a table.
 You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows
would be updated.
Syntax: Following is an example, which would update ADDRESS for a customer whose ID is 6:

sqlite> UPDATE COMPANY SET ADDRESS ='Texas' WHERE ID =6;

Now, COMPANY table would have the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------

Department of Computer Science Page 18


1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 Texas 45000.0
7 James 24 Houston 10000.0

 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:

sqlite> UPDATE COMPANY SET ADDRESS ='Texas', SALARY =20000.00;

 Now, COMPANY table will have the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 Texas 20000.0
2 Allen 25 Texas 20000.0
3 Teddy 23 Texas 20000.0
4 Mark 25 Texas 20000.0
5 David 27 Texas 20000.0
6 Kim 22 Texas 20000.0
7 James 24 Texas 20000.0

SQLite - DELETE Query


 The SQLite DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete selected rows, otherwise all the records would be
deleted.
Syntax:
 The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

 You can combine N number of conditions using AND or OR operators.


Example:
 Consider COMPANY table is having the following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------

Department of Computer Science Page 19


1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0

 Following is an example, which would DELETE a customer whose ID is 7:

sqlite> DELETE FROM COMPANY WHERE ID =7;

 Now COMPANY table will have following records:

ID NAME AGE ADDRESS SALARY


---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0

 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:

sqlite> DELETE FROM COMPANY;

 Now, COMPANY table does not have any record because all the records have been deleted by
DELETE statement.

PDO EXTENSION

 PDO - PHP Data Object.


 An interface for accessing databases in PHP.
 Provides a vendor-neutral lightweight data-access abstraction layer.
 We cannot perform any database functions using the PDO extension by itself; we must use
a database-specific PDO driver to access a database server.
 PDO requires PHP Version 5.1 and available as a PECL extension for PHP 5.0.
 PDO requires the new object oriented features in the core of PHP 5, therefore it will not run with
earlier versions of PHP.

Department of Computer Science Page 20


Retrieving Data
PDO works by providing a standard set of functions for common database operations such as connecting,
querying, result set processing and error handling, and internally translating these functions to nativeAPI
calls understood by the database in use.
 consider the following example, which executes a SELECTquery and displays the records
found:
EXMPLE:
<?php
//attempt aconnection try {
$pdo= newPDO('mysql:dbname=music;host=localhost','user','pass');
} catch(PDOException$e)
{
die("ERROR:Could notconnect:". $e->getMessage());
}
//create andexecuteSELECT query
$sql= "SELECT artist_id,artist_nameFROM artists";
if($result= $pdo->query($sql))
{
while($row= $result->fetch())
{
echo$row[0] .":".$row[1]."\n";
}
} else
{
echo"ERROR: Could not execute $sql.". print_r($pdo->errorInfo());
}
//closeconnection
unset($pdo);
?>

using PDO to get data from a database involves steps


The first step is to initialize an instance of the PDO class and pass the object constructor three arguments: a
Data Source Name (DSN) string indicating the type of database to connect to as well as other database-
specific options, a valid database username, and the corresponding password.
list some common DSN string formats.

Department of Computer Science Page 21


Database DSNString
MySQL 'mysql:host=host;port=port;dbname=db'
SQLite 'sqlite:path/to/database/file'
PostgreSQ 'pgsql:host=host port=portdbname=dbuser=user
L
Oracle 'oci:dbname=//host:port/db'
Firebird 'firebird:User=user;Password=passDatabase=d
b; DataSource=host;Port=port'

 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

WOR KING WITH XML


 XML is a markup language that defines set of rules for encoding documents in a format that is both
human-readable and machine-readable.
 So what exactly is a markup language? Markup is information added to a document that enhances its
meaning in certain ways, in that it identifies the parts and how they relate to each other.
 More specifically, a markup language is a set of symbols that can be placed in the text of a document
to demarcate and label the parts of that document.
 following example shows how XML markup looks, when embedded in a piece of text:

Department of Computer Science Page 22


<message>
<text>Hello, world!</text>
</message>

 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.

Department of Computer Science Page 23


 A well-formed document follows all the rules for element and attribute names, contains all
essential declarations, contains one (and only one) root element, and follows a correctly nested
element hierarchy below the root element.
 A valid document is one which meets all the conditions of being well-formed and also conforms
to additional rules laid out in a Document Type Definition (DTD) or XML Schema.
XML Parsing Methods
 An XMLdocument is processed by a software application known as an XML parser.
 This parser reads the XML document using one of two approaches, the SimpleAPI for
XML(SAX) approach or the Document Object Model (DOM) approach:
 ASAX parser works by traversing an XML document sequentially, from beginning to end, and
calling specific user-defined functions as it encounters different types of XML constructs.
 ADOM parser, on the other hand, works by reading the entire XML document in one fell
swoop and converting it to a hierarchical “tree” structure in memory. The parser can then be
programmed to traverse the tree, jumping between “sibling” or “child” branches of the tree to
access specific pieces of information.
Simple XML Extension
 PHP has support for both DOM and SAX parsing methods, by far the easiest way to work with XML
data in PHPis via its Simple XML extension.
Working with Elements
 Simple XML represents every XML document as an object and turns the elements within it into a
hierarchical set of objects and object properties.
 Accessing a particular element now becomes as simple as using parent->childnotation to
traverse the object tree until that element is reached.
Example:
considerthefollowingXMLfile(address.xml):
<?xmlversion='1.0'?>
<address>
<street>13 HighStreet</street>
<county>Oxfordshire</county>
<city>
<name>Oxford</name>
<zip>OX11BA</zip>
</city>
<country>UK</country>
</address>

Department of Computer Science Page 24


 Here’s a PHP script that uses Simple XML to read this file and retrieve the city
name and ZIPcode:
<?php
//loadXML file
$xml =simplexml_load_file('address.xml')
ordie("UnabletoloadXML!");
//accessXML data
//output:'City: Oxford\n Postalcode:OX11BA\n'
echo"City: ". $xml->city->name."\n";
echo"Postal code:". $xml->city->zip."\n";
?>

 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)

Department of Computer Science Page 25


{
echo$book->title ."\n";
echo"Genre:". $book['genre']."\n";
echo"Rating: ". $book['rating']. "\n\n";
}
?>
 In this example, a foreachloop iterates over the <book>elements in the XMLdata, turning each
into an object.
 Attributes of the book element are represented as elements of an associative array and can thus be
accessed by key: the key 'genre'returns the value of the 'genre'attribute, and the key
'rating'returns the value of the 'rating' attribute.
Altering Element and Attribute Values
 With SimpleXML, it’s easy to change the content in an XMLfile: simply assign a new value to the
corresponding object property using PHP’s assignment operator (=).
 To illustrate, consider the following PHP script, which changes the title and author of the second
book in library.xml and then outputs the revised XML document:
EXAMPLE:
<?php
//loadXML file
$xml =simplexml_load_file('library.xml') ordie("Unableto
loadXML!");
//changeelementvalues
//setnew titleandauthor for secondbook
$xml->book[1]->title= 'InvisiblePrey';
$xml->book[1]->author= 'JohnSandford';
//outputnew XMLstring
header('Content-Type:text/xml');
echo $xml->asXML();
?>

Using PHP’s DOM Extension


 This extension, which is also enabled by default in PHP5, provides a stylish toolkit that complies
with the DOM Level 3 standard and brings comprehensive XML parsing capabilities to PHP.
Working with Elements
 The DOM parser works by reading an XML document and creating objects to represent the

Department of Computer Science Page 26


different parts of that document. Each of these objects comes with specific methods and
properties, which can be used to manipulate and access information about it.
 Thus,the entire XML document is represented as a “tree” of these objects, with the DOM parser
providing a simple API to move between the different branches of the tree.
 To illustrate how this works in practice, let’s revisit the address.xml file from the preceding
section:

<?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'

Department of Computer Science Page 27


echo"Postal code:". $root->childNodes->item(2)->childNodes->item(1)-
>nodeValue."\n";
//output:'Country:UK \n City: Oxford\n Postal code:OX11BA'
?>
 The first step is always to initialize an instance of the DOM Document object, which represents
an XML document.
 Once this object has been initialized, it can be used to parse an XML file via its load()method,
which accepts the disk path to the target XML file.
 Once the XML document has been load()-ed, it calls the DOM Document object’s
firstChildproperty, which returns a DOM Node object representing the root element
<address>.
 This DOM Node object, in turn, has a childNodesproperty, which returns a collection of all
the child elements of <address>.
 Individual elements of this collection can be accessed via their index position using the
item()method, with indexing starting from zero.
 These elements are again represented as DOM Node objects; as such, their names and values are
therefore accessible via their node Name and node Value properties.
 Thus,theelement<country>,which is the fourth child element under<address>, is accessible
via the path $root->childNodes->item(3),and the text value of this element,'UK',is
accessible via the path $root->childNodes->item(3)->node Value.
 Similarly,the element<name>, which is the first child of the <city>element,is accessible via the
path $root->child Nodes->item(2)->child Nodes->item(0) ,and the text
value'Oxford'is accessible via the path $root->childNodes->item(2)-
>childNodes->item(0)->nodeValue.

DOM relationships
Working with Attributes
 The DOM also includes extensive support for attributes: every DOM Element object comes with a

Department of Computer Science Page 28


getAttribute()method, which accepts an attribute name and returns the corresponding value.
example, which prints each book’s rating and genre from library.xml:
<?php
//initializenew DOMDocument
$doc= new DOMDocument();
//disable whitespace-onlytext nodes
$doc->preserveWhiteSpace= false;
//readXML file
$doc->load('library.xml');
//getcollection of<book>elements
//for eachbook
//retrieve andprint'genre'and'rating'attributes
//output: 'TheShining\nGenre:horror\nRating:5 \n\n...'
$books= $doc->getElementsByTagName('book');
foreach($booksas $book){
$title= $book->getElementsByTagName('title')->item(0)->nodeValue;
$rating= $book->getAttribute('rating');
$genre= $book->getAttribute('genre');
echo"$title\n";
echo"Genre:$genre\n";
echo"Rating:$rating\n\n";
}
?>
QUESTION BANK

UNIT V

2 MARKS

1. What are the features of php databases?


2. What is table?
3. What is primary key?
4. What is record?
5. What is database?
6. What is foreign key?
7. Define normalization.
8. What are the categories of SQL statements?
9. Give some examples of SQL statements.
10. How will you create a table in my sql?
11. What are the data type of attributes in my sql?

Department of Computer Science Page 29


12. How will you insert in the mysql database?
13. How will you select datas in the mysql database?
14. How will you delete the data’s in the mysql database?
15. How will you update data’s in the sql database?
16. How will you get the data’s from the mysql database?
17. What are the error handling methods in php?
18. How will you create custom error handler?
19. What is the use of set error handler?
20. What is the use of trigger error handler?
21. What is the use of se error handler?
22. What are the possible error types?
23. What are the key words are used as the exception handler in php?
24. What are the exception classes?
25. What is SQLLite?
26. What are the SQLLite commands?
27. How will you create SQLLite database?
28. How will you insert the datas into the SQLLite database?
29. How will you drop the SQLLite table?
30. How will you delete the SQLLite table?
31. What is PDO extension?
32. Define XML?
33. What are the XML Technologies?
34. Define Well formed and valid formed document.
35. What are the XML parsing approaches?

5 MARKS AND 10 MARKS

1. Write notes on databases and sql.


2. What are the steps to access My SQL databases?
3. What are the error handling methods available in php?
4. Explain SQlLite Extension.
5. Discuss about XML and its functions.
6. Explain about DOM Extension.

Department of Computer Science Page 30

You might also like