home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Programming PHPProgramming PHPSearch this book

8.2. Relational Databases and SQL

A Relational Database Management System (RDBMS) is a server that manages data for you. The data is structured into tables, where each table has some number of columns, each of which has a name and a type. For example, to keep track of James Bond movies, we might have a "movies" table that records the title (a string), year of release (a number), and the actor who played Bond in each movie (an index into a table of Bond actors).

Tables are grouped together into databases, so a James Bond database might have tables for movies, actors playing Bond, and villains. An RDBMS usually has its own user system, which controls access rights for databases (e.g., "user Fred can update database Bond").

PHP communicates with relational databases such as MySQL and Oracle using the Structured Query Language (SQL). You can use SQL to create, modify, and query relational databases.

The syntax for SQL is divided into two parts. The first, Data Manipulation Language, or DML, is used to retrieve and modify data in an existing database. DML is remarkably compact, consisting of only four verbs: select, insert, update, and delete. The set of SQL commands, used to create and modify the database structures that hold the data, is known as Data Definition Language, or DDL. The syntax for DDL is not as standardized as that for DML, but as PHP just sends any SQL commands you give it to the database, you can use any SQL commands your database supports.

Assuming you have a table called movies, this SQL statement would insert a new row:

INSERT INTO movies VALUES(0, 'Moonraker', 1979, 2)

This SQL statement inserts a new row but lists the columns for which there are values:

INSERT INTO movies (title, year, actor) VALUES ('Octopussy', 1982, 2)

To delete all movies from 1979, we could use this SQL statement:

DELETE FROM movies WHERE year=1979

To change the year for Octopussy to 1983, use this SQL statement:

UPDATE movies SET year=1983 WHERE title='Octopussy'

To fetch only the movies made in the 1980s, use:

SELECT * FROM movies WHERE year >= 1980 AND year < 1990

You can also specify the fields you want returned. For example:

SELECT title, year FROM movies WHERE year >= 1980 AND year < 1990

You can issue queries that bring together information from multiple tables. For example, this query joins together the movie and actor tables to let us see who starred in each movie:

SELECT movies.title, movies.year, actors.name
FROM movies,actors WHERE movies.star = actors.id
                   AND year >= 1980 AND year < 1990

For more on SQL, see SQL in a Nutshell, by Kevin Kline (O'Reilly).

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.