28
DATABASE PROGRAMMING Henry Osborne

Database Programming

Embed Size (px)

DESCRIPTION

PHP provides access to a great number of different database systems, many of which are relational in nature and can be interrogated using Structured Query Language (SQL).

Citation preview

Page 1: Database Programming

DATABASE PROGRAMMINGHenry Osborne

Page 2: Database Programming

DATABASE

A comprehensive collection of related data organized for convenient access, generally in a computer

Page 3: Database Programming

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

Page 4: Database Programming

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

Page 5: Database Programming

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

Page 6: Database Programming

DATA TYPES

int or integer

Signed integer number, 32 bits in length.

smallint Signed integer number, 16 bits in length.real Signed floating-point number, 32 bits in

length.float Signed floating-point number, 64 bits in

length.char Fixed-length character string.varchar Variable-length character string.

Page 7: Database Programming

CREATING DATABASES

CREATE DATABASE <dbname>;CREATE SCHEMA <dbname>;

Page 8: Database Programming

CREATE TABLES

CREATE TABLE <tablename> (<col1name> <col1type> [<col1attributes>],[...<colnname> <colntype> [<colnattributes>]]

);

Page 9: Database Programming

CREATE TABLES

CREATE TABLE book (id INT NOT NULL PRIMARY KEY,isbn VARCHAR(13),title VARCHAR(255),author VARCHAR(255),publisher VARCHAR(255)

);

Page 10: Database Programming

CREATING INDICES AND RELATIONSHIPS

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

CREATE INDEX book_isbn ON book (isbn);

Page 11: Database Programming

CREATING INDICES AND RELATIONSHIPS

CREATE TABLE book_chapter (isbn VARCHAR(13) REFERENCES book (id),chapter_number INT NOT NULL,chapter_title VARCHAR(255)

);

Page 12: Database Programming

DROPPING OBJECTS

DROP TABLE book_chapter;

DROP SCHEMA my_book_database;

Page 13: Database Programming

ADDING/MANIPULATING DATA

INSERT INTO <tablename> VALUES (<field1value>[, ..., <fieldnvalue>]);

OR

INSERT INTO <tablename>(<field1>[, ..., <fieldn>])VALUES(<field1value>[, ..., <fieldnvalue>]);

Page 14: Database Programming

ADDING/MANIPULATING DATA

INSERT INTO book (isbn, title, author)VALUES (’0812550706’, ’Ender\’s Game’, ’Orson Scott Card’);

Page 15: Database Programming

ADDING/MANIPULATING DATA

To update records, you can use the UPDATE statement.

UPDATE bookSET publisher = ’Tor Science Fiction’, author = ’Orson S. Card’WHERE isbn = ’0812550706’;

Page 16: Database Programming

REMOVE DATA

DELETE FROM book;

DELETE FROM book WHERE isbn = ’0812550706’;

Page 17: Database Programming

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’;

Page 18: Database Programming

SQL JOINS

SELECT *FROM book INNER JOIN book_chapterON book.isbn = book_chapter.isbn;

Page 19: Database Programming

OUTER JOINS

SELECT book.title, author.last_nameFROM authorLEFT JOIN book ON book.author_id = author.id;

Page 20: Database Programming

OUTER JOINS

SELECT book.title, author.last_nameFROM authorRIGHT JOIN book ON book.author_id = author.id;

Page 21: Database Programming

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

Page 22: Database Programming

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.

Page 23: Database Programming

DATABASE CONNECTION

$dsn = ’mysql:host=localhost;dbname=library’;$dbh = new PDO($dsn, ’dbuser’, ’dbpass’);

Page 24: Database Programming

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();

}

Page 25: Database Programming

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

}

Page 26: Database Programming

DATABASE QUERY WITH PDO

$results = $dbh->query($sql);

$results->setFetchMode(PDO::FETCH_OBJ);

foreach ($results as $row)

{

echo "{$row->title}, {$row->last_name}\n";

}

Page 27: Database Programming

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

Page 28: Database Programming

DATABASE PROGRAMMING