SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Introduction & history of dbms
Introduction & history of dbmsIntroduction & history of dbms
Introduction & history of dbms
sethu pm
 
Lecture 01 introduction to database
Lecture 01 introduction to databaseLecture 01 introduction to database
Lecture 01 introduction to database
emailharmeet
 

Mais procurados (20)

The Relational Database Model
The Relational Database ModelThe Relational Database Model
The Relational Database Model
 
The Relational Model
The Relational ModelThe Relational Model
The Relational Model
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
 
Rdbms
RdbmsRdbms
Rdbms
 
data modeling and models
data modeling and modelsdata modeling and models
data modeling and models
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database system
 
Introduction to RDBMS
Introduction to RDBMSIntroduction to RDBMS
Introduction to RDBMS
 
File systems versus a dbms
File systems versus a dbmsFile systems versus a dbms
File systems versus a dbms
 
Introduction & history of dbms
Introduction & history of dbmsIntroduction & history of dbms
Introduction & history of dbms
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Lecture 01 introduction to database
Lecture 01 introduction to databaseLecture 01 introduction to database
Lecture 01 introduction to database
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Database management system
Database management system Database management system
Database management system
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 

Semelhante a Database Programming

xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
WrushabhShirsat3
 
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
 
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
APMRETAIL
 

Semelhante a 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
 

Mais de Henry Osborne

Mais de 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
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 

Último (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

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

Notas do Editor

  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.