SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Distributed database management system
Distributed database management  systemDistributed database management  system
Distributed database management systemPooja Dixit
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database systemphilipsinter
 
Database Administration
Database AdministrationDatabase Administration
Database AdministrationBilal Arshad
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sqlDhani Ahmad
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Salman Memon
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbmsNaresh Kumar
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagramssadique_ghitm
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database DesignArchit Saxena
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMSkoolkampus
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Software Cost Estimation Techniques
Software Cost Estimation TechniquesSoftware Cost Estimation Techniques
Software Cost Estimation TechniquesSanthi thi
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMSkoolkampus
 
SWE-401 - 6. Software Analysis and Design Tools
SWE-401 - 6. Software Analysis and Design ToolsSWE-401 - 6. Software Analysis and Design Tools
SWE-401 - 6. Software Analysis and Design Toolsghayour abbas
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational modelChirag vasava
 
Lecture-1: Introduction to web engineering - course overview and grading scheme
Lecture-1: Introduction to web engineering - course overview and grading schemeLecture-1: Introduction to web engineering - course overview and grading scheme
Lecture-1: Introduction to web engineering - course overview and grading schemeMubashir Ali
 
Memory management
Memory managementMemory management
Memory managementRajni Sirohi
 

Was ist angesagt? (20)

Distributed database management system
Distributed database management  systemDistributed database management  system
Distributed database management system
 
Basic DBMS ppt
Basic DBMS pptBasic DBMS ppt
Basic DBMS ppt
 
Recovery techniques
Recovery techniquesRecovery techniques
Recovery techniques
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database system
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Database Administration
Database AdministrationDatabase Administration
Database Administration
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
 
Sql fundamentals
Sql fundamentalsSql fundamentals
Sql fundamentals
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagrams
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database Design
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMS
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Software Cost Estimation Techniques
Software Cost Estimation TechniquesSoftware Cost Estimation Techniques
Software Cost Estimation Techniques
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMS
 
SWE-401 - 6. Software Analysis and Design Tools
SWE-401 - 6. Software Analysis and Design ToolsSWE-401 - 6. Software Analysis and Design Tools
SWE-401 - 6. Software Analysis and Design Tools
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
Lecture-1: Introduction to web engineering - course overview and grading scheme
Lecture-1: Introduction to web engineering - course overview and grading schemeLecture-1: Introduction to web engineering - course overview and grading scheme
Lecture-1: Introduction to web engineering - course overview and grading scheme
 
Memory management
Memory managementMemory management
Memory management
 

Ă„hnlich wie Database Programming

Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptxmebratu9
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptxNilamHonmane
 
Php 2
Php 2Php 2
Php 2tnngo2
 
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
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql Subhasis Nayak
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(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
 
Hsqldb tutorial
Hsqldb tutorialHsqldb tutorial
Hsqldb tutorialSrikrishna k
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slidesenosislearningcom
 

Ă„hnlich wie 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
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
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...
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(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
 

Mehr von 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
 
Interface Design
Interface DesignInterface Design
Interface DesignHenry Osborne
 
Universal Usability
Universal UsabilityUniversal Usability
Universal UsabilityHenry Osborne
 
Website Security
Website SecurityWebsite Security
Website SecurityHenry 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
 
Web Programming
Web ProgrammingWeb Programming
Web ProgrammingHenry 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
 

Mehr von 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
 

KĂĽrzlich hochgeladen

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...liera silvan
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
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
 

KĂĽrzlich hochgeladen (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
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
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 

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}";

Hinweis der Redaktion

  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.