SlideShare a Scribd company logo
1 of 28
DATABASE
PROGRAMMING
Henry Osborne
DATABASE

A comprehensive collection of
related data organized for
convenient access, generally in a
computer
RELATIONAL DATABASE
A relational database is a collection of data items
organized as a set of formally-described tables from
which data can be accessed or reassembled in
many different ways without having to reorganize the
database tables. The relational database was
invented by E. F. Codd at IBM in 1970.
http://searchsqlserver.techtarget.com/definition/relational-database
INDICES
• Make it possible to organize the data in a table according
to one or more columns.
• One of the cardinal elements of relational databases
• Can usually be created on one or more columns of a table
• Can also be declared as unique
• Primary keys are a special type of unique index that is used
to determine the “natural” method of uniquely identifying a
row in a table
RELATIONSHIPS
• One-to-one: at most, one row in the child table can
correspond to each row in the parent table
• One-to-many: an arbitrary number of rows in the child table
can correspond to any one row in the parent table
• Many-to-many: an arbitrary number of rows in the child
table can correspond to an arbitrary number of rows in the
parent table
DATA TYPES
int or integer
smallint
real
float
char
varchar

Signed integer number, 32 bits in length.
Signed integer number, 16 bits in length.
Signed floating-point number, 32 bits in length.
Signed floating-point number, 64 bits in length.
Fixed-length character string.
Variable-length character string.
CREATING DATABASES
CREATE DATABASE <dbname>;
CREATE SCHEMA <dbname>;
CREATE TABLES
CREATE TABLE <tablename> (
<col1name> <col1type> [<col1attributes>],
[...
<colnname> <colntype> [<colnattributes>]]
);
CREATE TABLES
CREATE TABLE book (
id INT NOT NULL PRIMARY KEY,
isbn VARCHAR(13),
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255)

);
CREATING INDICES AND
RELATIONSHIPS
CREATE INDEX <indexname>
ON <tablename> (<column1>[, ..., <columnn>]);

CREATE INDEX book_isbn ON book (isbn);
CREATING INDICES AND
RELATIONSHIPS
CREATE TABLE book_chapter (
isbn VARCHAR(13) REFERENCES book (id),
chapter_number INT NOT NULL,
chapter_title VARCHAR(255)

);
DROPPING OBJECTS
DROP TABLE book_chapter;

DROP SCHEMA my_book_database;
ADDING/MANIPULATING DATA
INSERT INTO <tablename> VALUES
(<field1value>[, ..., <fieldnvalue>]);
OR
INSERT INTO <tablename>
(<field1>[, ..., <fieldn>])
VALUES
(<field1value>[, ..., <fieldnvalue>]);
ADDING/MANIPULATING DATA
INSERT INTO book (isbn, title, author)
VALUES (’0812550706’, ’Ender’s Game’, ’Orson Scott Card’);
ADDING/MANIPULATING DATA
To update records, you can use the UPDATE statement.
UPDATE book
SET publisher = ’Tor Science Fiction’, author = ’Orson S. Card’
WHERE isbn = ’0812550706’;
REMOVE DATA
DELETE FROM book;

DELETE FROM book WHERE isbn = ’0812550706’;
RETRIEVE DATA
SELECT * FROM book;
SELECT * FROM book WHERE author = ’Ray Bradbury’;

SELECT * FROM book
WHERE author = ’Ray Bradbury’ OR author = ’George Orwell’;
SELECT * FROM book
WHERE author = ’Ray Bradbury’ AND publisher LIKE ’%Del Ray’;
SQL JOINS

SELECT *
FROM book INNER JOIN book_chapter
ON book.isbn = book_chapter.isbn;
OUTER JOINS
SELECT book.title, author.last_name
FROM author
LEFT JOIN book ON book.author_id = author.id;
OUTER JOINS
SELECT book.title, author.last_name
FROM author
RIGHT JOIN book ON book.author_id =
author.id;
PHP DATA OBJECTS (PDO)
• The standard distribution of PHP 5.1 and greater includes
PDO and the drivers for SQLite by default
• There are many other database drivers for PDO, including:
• Microsoft SQL Server
• Firebird
• MySQL
• Oracle
• PostgreSQL, and
• ODBC
PHP DATA OBJECTS (PDO)
• Once installed, the process for using each driver is,
for the most part, the same because PDO provides a
unified data access layer to each of these
database engines.
• There is no longer a need for separate mysql_query()
or pg_query() functions.
• PDO provides a single object-oriented interface to
these databases.
DATABASE CONNECTION
$dsn = ’mysql:host=localhost;dbname=library’;
$dbh = new PDO($dsn, ’dbuser’, ’dbpass’);
ERROR HANDLING
try {
$dsn = ’mysql:host=localhost;dbname=library’;
$dbh = new PDO($dsn, ’dbuser’, ’dbpass’);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// All other database calls go here

}
catch (PDOException $e)
{
echo ’Failed: ’ . $e->getMessage();
}
DATABASE QUERY WITH PDO
$author = ’’;
if (ctype_alpha($_GET[’author’])){
$author = $_GET[’author’];
}
// Escape the value of $author with quote()
$sql = ’SELECT author.*, book.* FROM author LEFT JOIN book ON author.id =
book.author_id WHERE author.last_name = ’ . $dbh->quote($author);
// Execute the statement and echo the results
$results = $dbh->query($sql);
foreach ($results as $row)

{
echo "{$row[’title’]}, {$row[’last_name’]}n";
}
DATABASE QUERY WITH PDO
$results = $dbh->query($sql);
$results->setFetchMode(PDO::FETCH_OBJ);
foreach ($results as $row)
{
echo "{$row->title}, {$row->last_name}n";
}
DATABASE QUERY WITH PDO
$sql = "INSERT INTO book (isbn, title, author_id,
publisher_id)
VALUES (’0395974682’, ’The Lord of the Rings’, 1,
3)";
$affected = $dbh->exec($sql);
echo "Records affected: {$affected}";
DATABASE
PROGRAMMING

More Related Content

What's hot

File access methods.54
File access methods.54File access methods.54
File access methods.54myrajendra
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class libraryPrem Kumar Badri
 
object oriented methodologies
object oriented methodologiesobject oriented methodologies
object oriented methodologiesAmith Tiwari
 
11. Storage and File Structure in DBMS
11. Storage and File Structure in DBMS11. Storage and File Structure in DBMS
11. Storage and File Structure in DBMSkoolkampus
 
File organization 1
File organization 1File organization 1
File organization 1Rupali Rana
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational modelChirag vasava
 
Lecture 01 introduction to database
Lecture 01 introduction to databaseLecture 01 introduction to database
Lecture 01 introduction to databaseemailharmeet
 
Database management systems components
Database management systems componentsDatabase management systems components
Database management systems componentsmuhammad bilal
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database systemphilipsinter
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMSkoolkampus
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
Rdbms
RdbmsRdbms
Rdbmsrdbms
 

What's hot (20)

C# Private assembly
C# Private assemblyC# Private assembly
C# Private assembly
 
Temporal databases
Temporal databasesTemporal databases
Temporal databases
 
File access methods.54
File access methods.54File access methods.54
File access methods.54
 
Database Chapter 3
Database Chapter 3Database Chapter 3
Database Chapter 3
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class library
 
object oriented methodologies
object oriented methodologiesobject oriented methodologies
object oriented methodologies
 
11. Storage and File Structure in DBMS
11. Storage and File Structure in DBMS11. Storage and File Structure in DBMS
11. Storage and File Structure in DBMS
 
Database, Lecture-1.ppt
Database, Lecture-1.pptDatabase, Lecture-1.ppt
Database, Lecture-1.ppt
 
File organization 1
File organization 1File organization 1
File organization 1
 
Data Models
Data ModelsData Models
Data Models
 
Rdbms
RdbmsRdbms
Rdbms
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
UML
UMLUML
UML
 
Lecture 01 introduction to database
Lecture 01 introduction to databaseLecture 01 introduction to database
Lecture 01 introduction to database
 
Database management systems components
Database management systems componentsDatabase management systems components
Database management systems components
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database system
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMS
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Rdbms
RdbmsRdbms
Rdbms
 
Deductive databases
Deductive databasesDeductive databases
Deductive databases
 

Similar to Database Programming

Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptxmebratu9
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...DicodingEvent
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Subhasis Nayak
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql Subhasis Nayak
 
Introduction to Apache Hive(Big Data, Final Seminar)
Introduction to Apache Hive(Big Data, Final Seminar)Introduction to Apache Hive(Big Data, Final Seminar)
Introduction to Apache Hive(Big Data, Final Seminar)Takrim Ul Islam Laskar
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptxnatesanp1234
 
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdf
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdfRelational database was proposed by Edgar Codd (of IBM Research) aro.pdf
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdfAPMRETAIL
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQLJoel Brewer
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slidesenosislearningcom
 

Similar to Database Programming (20)

MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
 
MySQL with PHP
MySQL with PHPMySQL with PHP
MySQL with PHP
 
lecture_34e.pptx
lecture_34e.pptxlecture_34e.pptx
lecture_34e.pptx
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Php 2
Php 2Php 2
Php 2
 
Hive Hadoop
Hive HadoopHive Hadoop
Hive Hadoop
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Introduction to Apache Hive(Big Data, Final Seminar)
Introduction to Apache Hive(Big Data, Final Seminar)Introduction to Apache Hive(Big Data, Final Seminar)
Introduction to Apache Hive(Big Data, Final Seminar)
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdf
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdfRelational database was proposed by Edgar Codd (of IBM Research) aro.pdf
Relational database was proposed by Edgar Codd (of IBM Research) aro.pdf
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Hsqldb tutorial
Hsqldb tutorialHsqldb tutorial
Hsqldb tutorial
 
Php summary
Php summaryPhp summary
Php summary
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slides
 

More from Henry Osborne

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android FundamentalsHenry Osborne
 
Open Source Education
Open Source EducationOpen Source Education
Open Source EducationHenry Osborne
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - LinuxHenry Osborne
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with LinuxHenry Osborne
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in LinuxHenry Osborne
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 CanvasHenry Osborne
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia SupportHenry Osborne
 
Information Architecture
Information ArchitectureInformation Architecture
Information ArchitectureHenry Osborne
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web ServicesHenry Osborne
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented DesignHenry Osborne
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and PatternsHenry Osborne
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and EventsHenry Osborne
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web PresenceHenry Osborne
 

More from Henry Osborne (20)

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Open Source Education
Open Source EducationOpen Source Education
Open Source Education
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - Linux
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with Linux
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in Linux
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia Support
 
Information Architecture
Information ArchitectureInformation Architecture
Information Architecture
 
Interface Design
Interface DesignInterface Design
Interface Design
 
Universal Usability
Universal UsabilityUniversal Usability
Universal Usability
 
Website Security
Website SecurityWebsite Security
Website Security
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web Services
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented Design
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Web Programming
Web ProgrammingWeb Programming
Web Programming
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web Presence
 

Recently uploaded

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Recently uploaded (20)

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

Database Programming

  • 2. DATABASE A comprehensive collection of related data organized for convenient access, generally in a computer
  • 3. RELATIONAL DATABASE A relational database is a collection of data items organized as a set of formally-described tables from which data can be accessed or reassembled in many different ways without having to reorganize the database tables. The relational database was invented by E. F. Codd at IBM in 1970. http://searchsqlserver.techtarget.com/definition/relational-database
  • 4. INDICES • Make it possible to organize the data in a table according to one or more columns. • One of the cardinal elements of relational databases • Can usually be created on one or more columns of a table • Can also be declared as unique • Primary keys are a special type of unique index that is used to determine the “natural” method of uniquely identifying a row in a table
  • 5. RELATIONSHIPS • One-to-one: at most, one row in the child table can correspond to each row in the parent table • One-to-many: an arbitrary number of rows in the child table can correspond to any one row in the parent table • Many-to-many: an arbitrary number of rows in the child table can correspond to an arbitrary number of rows in the parent table
  • 6. DATA TYPES int or integer smallint real float char varchar Signed integer number, 32 bits in length. Signed integer number, 16 bits in length. Signed floating-point number, 32 bits in length. Signed floating-point number, 64 bits in length. Fixed-length character string. Variable-length character string.
  • 7. CREATING DATABASES CREATE DATABASE <dbname>; CREATE SCHEMA <dbname>;
  • 8. CREATE TABLES CREATE TABLE <tablename> ( <col1name> <col1type> [<col1attributes>], [... <colnname> <colntype> [<colnattributes>]] );
  • 9. CREATE TABLES CREATE TABLE book ( id INT NOT NULL PRIMARY KEY, isbn VARCHAR(13), title VARCHAR(255), author VARCHAR(255), publisher VARCHAR(255) );
  • 10. CREATING INDICES AND RELATIONSHIPS CREATE INDEX <indexname> ON <tablename> (<column1>[, ..., <columnn>]); CREATE INDEX book_isbn ON book (isbn);
  • 11. CREATING INDICES AND RELATIONSHIPS CREATE TABLE book_chapter ( isbn VARCHAR(13) REFERENCES book (id), chapter_number INT NOT NULL, chapter_title VARCHAR(255) );
  • 12. DROPPING OBJECTS DROP TABLE book_chapter; DROP SCHEMA my_book_database;
  • 13. ADDING/MANIPULATING DATA INSERT INTO <tablename> VALUES (<field1value>[, ..., <fieldnvalue>]); OR INSERT INTO <tablename> (<field1>[, ..., <fieldn>]) VALUES (<field1value>[, ..., <fieldnvalue>]);
  • 14. ADDING/MANIPULATING DATA INSERT INTO book (isbn, title, author) VALUES (’0812550706’, ’Ender’s Game’, ’Orson Scott Card’);
  • 15. ADDING/MANIPULATING DATA To update records, you can use the UPDATE statement. UPDATE book SET publisher = ’Tor Science Fiction’, author = ’Orson S. Card’ WHERE isbn = ’0812550706’;
  • 16. REMOVE DATA DELETE FROM book; DELETE FROM book WHERE isbn = ’0812550706’;
  • 17. RETRIEVE DATA SELECT * FROM book; SELECT * FROM book WHERE author = ’Ray Bradbury’; SELECT * FROM book WHERE author = ’Ray Bradbury’ OR author = ’George Orwell’; SELECT * FROM book WHERE author = ’Ray Bradbury’ AND publisher LIKE ’%Del Ray’;
  • 18. SQL JOINS SELECT * FROM book INNER JOIN book_chapter ON book.isbn = book_chapter.isbn;
  • 19. OUTER JOINS SELECT book.title, author.last_name FROM author LEFT JOIN book ON book.author_id = author.id;
  • 20. OUTER JOINS SELECT book.title, author.last_name FROM author RIGHT JOIN book ON book.author_id = author.id;
  • 21. PHP DATA OBJECTS (PDO) • The standard distribution of PHP 5.1 and greater includes PDO and the drivers for SQLite by default • There are many other database drivers for PDO, including: • Microsoft SQL Server • Firebird • MySQL • Oracle • PostgreSQL, and • ODBC
  • 22. PHP DATA OBJECTS (PDO) • Once installed, the process for using each driver is, for the most part, the same because PDO provides a unified data access layer to each of these database engines. • There is no longer a need for separate mysql_query() or pg_query() functions. • PDO provides a single object-oriented interface to these databases.
  • 23. DATABASE CONNECTION $dsn = ’mysql:host=localhost;dbname=library’; $dbh = new PDO($dsn, ’dbuser’, ’dbpass’);
  • 24. ERROR HANDLING try { $dsn = ’mysql:host=localhost;dbname=library’; $dbh = new PDO($dsn, ’dbuser’, ’dbpass’); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // All other database calls go here } catch (PDOException $e) { echo ’Failed: ’ . $e->getMessage(); }
  • 25. DATABASE QUERY WITH PDO $author = ’’; if (ctype_alpha($_GET[’author’])){ $author = $_GET[’author’]; } // Escape the value of $author with quote() $sql = ’SELECT author.*, book.* FROM author LEFT JOIN book ON author.id = book.author_id WHERE author.last_name = ’ . $dbh->quote($author); // Execute the statement and echo the results $results = $dbh->query($sql); foreach ($results as $row) { echo "{$row[’title’]}, {$row[’last_name’]}n"; }
  • 26. DATABASE QUERY WITH PDO $results = $dbh->query($sql); $results->setFetchMode(PDO::FETCH_OBJ); foreach ($results as $row) { echo "{$row->title}, {$row->last_name}n"; }
  • 27. DATABASE QUERY WITH PDO $sql = "INSERT INTO book (isbn, title, author_id, publisher_id) VALUES (’0395974682’, ’The Lord of the Rings’, 1, 3)"; $affected = $dbh->exec($sql); echo "Records affected: {$affected}";

Editor's Notes

  1. SQL supports a number of data types, which provide a greater degree of flexibility than PHP in how the data is stored and representedchar string will always have a fixed length, regardless of how many characters it contains (the string is usually padded with spaces to the column’s length). In both cases, however, a string column must be given a length (usually between 1 and 255 characters, al-though some database systems do not follow this rule), which means that any string coming from PHP, where it can have an arbitrary length, can be truncated, usually without even a warning, thus resulting in the loss of data.Most database systems also define an arbitrary-length character data type (usually called text) that most closely resembles PHP’s strings. However, this data type usually comes with a number of strings attached (such as a maximum allowed length and severe limitations on search and indexing capabilities). Therefore, you will still be forced to use char and (more likely) varchar, with all of their limitations.
  2. The formal definition of database schema is a set of formulas (sentences) called integrity constraints imposed on a database. These integrity constraints ensure compatibility between parts of the schema. All constraints are expressible in the same language. ~http://en.wikipedia.org/wiki/Database_schema
  3. Indices can be created (as was the example with the primary key above) while you are creating a table; alternatively, you can create them separately at a later point in time
  4. Foreign-key relationships are created either when a table is created, or at a later date with an altering statement. For example, suppose we wanted to add a table that contains a list of all of the chapter titles for every bookThis code creates a one-to-many relationship between the parent table book and the child table book_chapter based on the isbn field. Once this table is created, you can only add a row to it if the ISBN you specify exists in book.
  5. The act of deleting an object from a schema—be it a table, an index, or even the schema itself—is called dropping. It is performed by a variant of the DROP statementA good database system that supports referential integrity will not allow you to drop a table if doing so would break the consistency of your data. Thus, deleting the book table cannot take place until book_chapter is dropped first.The same technique can be used to drop an entire schema
  6. The first form of the INSERT statement is used when you want to provide values for every column in your table—in this case, the column values must be specified in the same order in which they appear in the table declaration.In its second form, the INSERT statement consists of three main parts. The first part tells the database engine into which table to insert the data. The second part indicates the columns for which we’re providing a value; finally, the third part contains the actual data to insert.
  7. DELETE FROM book;This simple statement will remove all records from the book table, leaving behind an empty table.
  8. To retrieve data from any SQL database engine, you must use a SELECT statement; SELECT statements range from very simple to incredibly complex, depending on your needsSELECT * FROM bookWHERE author = ’Ray Bradbury’ OR author = ’George Orwell’;SELECT * FROM bookWHERE author = ’Ray Bradbury’ AND publisher LIKE ’%Del Ray’;The first example statement contains an OR clause and, thus, broadens the results to return all books by each author, while the second statement further restricts the results with an AND clause to all books by the author that were also published by a specific publisher. Note, here, the use of the LIKE operator, which provides a case-insensitive match and allows the use of the % wild character to indicate an arbi-trary number of characters. Thus, the expression AND publisher LIKE ’%Del Ray’ will match any publisher that ends in the string del ray, regardless of case.
  9. Joins combine data from multiple tables to create a single recordset.There are two basic types of joins: inner joins and outer joins. In both cases, joins create a link between two tables based on a common set of columns (keys).An inner join returns rows from both tables only if keys from both tables can be found that satisfies the join conditions.
  10. Outer joins return all records from one table, while restricting the other table to matching records, which means that some of the columns in the results will contain NULL values.Left joins are a type of outer join in which every record in the left table that matches the WHERE clause (if there is one) will be returned regardless of a match made in the ON clause of the right table.
  11. Right joins are analogous to left joins—only reversed: instead of returning all results from the “left” side, the right join returns all results from the “right” side, restricting results from the “left” side to matches of the ON clause.Here, the table on the left is still the author table, and the right table is still the book table, but, this time, the results returned will include all records from the book table and only those from the author table that match the ON clause where book.author_id = author.id
  12. To connect to a database, PDO requires at least a Data Source Name, or DSN, format-ted according to the driver used. Detailed DSN formatting documentation exists on the PHP Web site for each driver. Additionally, if your database requires a username or password, PDO will need these to access the database.
  13. This is not only a best practice, but it is very useful in debugging. Note that the default error mode for PDO is PDO::ERRMODE_SILENT, which means that it will not emit any warnings or error messages. For the examples the error mode is set to PDO::ERRMODE_EXECEPTION. This causes PDO to throw a PDOExecption when an error occurs. This exception can be caught and displayed for debugging purposes.
  14. To retrieve a result set from a database using PDO, use the PDO::query() method.To escape a value included in a query (e.g. from $_GET, $_POST, $_COOKIE, etc.) use the PDO::quote() method. PDO will ensure that the string is quoted properly for the database used.The method PDO::query() returns a PDOStatement object.
  15. By default, the fetch mode for a PDOStatement is PDO::FETCH_BOTH, which means that it will return an array containing both associative and numeric indexes. It is possible to change the PDOStatement object to return, for example, an object instead of an array so that each column in the result set may be accessed as properties of an object instead of array indices.
  16. To execute an INSERT, UPDATE, or DELETE statement against a database, PDO provides the PDO::exec() method. The PDO::exec() method executes an SQL statement and returns the number of rows affected.