Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

Introduction to Databases

an official standard for the SQL language. In 1991, the X/Open and

SQL Access Group created a standardized version of SQL known as

the Common Applications Environment (CAE) SQL draft specifica-

tion. Even with two major standards available, however, most DBMSs

use their own version of the SQL language. MySQL corresponds

primarily to the ANSI SQL standard, although it includes a few of its

own extensions to the language.

SQL uses fairly easy-to-understand statements to execute database

commands. SQL statements are composed of keywords that perform

actions on a database. Table 7-1 lists several SQL keywords that are

common to most versions of SQL.

Keyword

DELETE

FROM

INSERT

INTO

ORDER BY

SELECT

UPDATE

WHERE

If you ever

work directly

with another

DBMS, keep

in mind that

the SQL you learn in this

chapter might not corre-

spond directly to that

DBMS’s version of SQL.

391

Description

Deletes a row from a table

Specifies the tables from which to retrieve or delete records

Inserts a new row into a table

Determines the table into which records should be inserted

Sorts the records returned from a table

Returns information from a table

Saves changes to fields in a record

Specifies the conditions that must be met for records to be

returned from a query

Common SQL keywords

You will

study many

of the basic

SQL key-

words in this

chapter. For in-depth

information on SQL state-

ments supported in

MySQL, refer to the

MySQL Reference Manual

at http://dev.mysql.com/

doc/mysql/en/index.

html.

Table 7-1

The simple SQL statement SELECT * FROM Employees returns all

fields (using the asterisk wildcard) from the Employees table. The fol-

lowing code shows a more complex SQL statement that selects the

last_name and first_name fields from the Employees table if the

record’s city field is equal to “Spencer.” The results are then sorted by

the last_name and first_name fields using the ORDER BY keyword.

Notice that commas separate multiple field names.

SELECT last_name, first_name FROM Employees

WHERE city = "Spencer" ORDER BY last_name, first_name;

Short Quiz

1.

Explain the difference between a flat-file database and a rela-

tional database.

Explain the relationship between a primary key and a foreign

key.

2.


CHAPTER 7

Working with Databases and MySQL

3.

Before con-

tinuing with

this chapter,

be sure that

you have

been provided access to

an account on a server

with a MySQL installation,

or that you have followed

the instructions in

Appendix B for installing

and testing one of the

xAMP packages.

MySQL

Monitor will

operate the

same regard-

less of

whether you use an SSH

connection, a telnet con-

nection, or a console

window on the server. For

the remainder of this

chapter, the term “con-

sole window” refers to

the window in which you

enter commands.

Several exam-

ples in this

chapter show

the contents

of a console

window and contain both

displayed text and text

that you enter. To distin-

guish between the two

types of text, the text that

you enter is shown in

bold, even though it won’t

appear in bold in the con-

sole window. Additionally,

the symbol [ENTER ] will

indicate where you need

to press the Enter key.

This symbol does not

actually appear on the

screen.

Describe the role of a junction (linking) table.

How does Open Database Connectivity (ODBC) assist in

database management?

Define the acronym SQL and explain its role in database

manipulation.

4.

392

5.

Getting Started with MySQL

As open source software, MySQL is a logical fit with Apache and

PHP, both of which are also developed as open source software. But

there are other reasons for MySQL’s popularity: It is also fast and

reliable, and it supports other programming languages besides PHP,

including C, C++, and Java. MySQL is also fairly easy to use and

install and is available on a number of different platforms.

There are several ways to interface with a MySQL database server

to access and manage your databases, including MySQL Monitor,

phpMyAdmin, and PHP database functions. The MySQL program

you will primarily use in this chapter is MySQL Monitor, which is

a command-line program for manipulating MySQL databases. You

execute the MySQL Monitor program with the mysql command,

which you run through an SSH connection, a telnet connection, or in

a console window on the server itself. Your instructor should provide

you with the information and tools needed to create a command-line

connection to the MySQL server.

In the next section, you will learn how to log in to MySQL.

Logging in to MySQL

To access or manipulate databases with MySQL programs such as

MySQL Monitor (mysql) or phpMyAdmin, you need to log in to

the MySQL database server. To use MySQL Monitor to log in to the

server, enter the following command:

mysql -h host -u user –p

In the preceding command, the -h argument allows you to specify

the host name where your MySQL database server is installed. The

default value for this argument is localhost, so if you are work-

ing with an instance of a MySQL database server that is installed on

your local computer, you do not need to specify the -h argument

and host name. However, if you are working with a MySQL database


Getting Started with MySQL

server on an ISP’s Web site, you need to enter your ISP’s host name.

The -u argument allows you to specify a user account name, and the

-p switch prompts you for a password. For example, the following

command logs the user name dongosselin into MySQL Monitor on a

UNIX installation of MySQL:

[dongosselin] $ mysql –h php_db -u dongosselin -p[ENTER ]

Enter password: **********[ENTER ]

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 6611 to server version: 4.1.9-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

393

You are

successfully

logged in

when you see

the mysql>

prompt.

To log in to MySQL Monitor:

1.

2.

Open a new console window.

Log in with the following command. Be sure to replace host

and user with the host name and user name provided by your

ISP or instructor.

mysql -h host -u user –p

When prompted, enter the password provided by your ISP or instruc-

tor. If you are working on a UNIX platform, your screen should look

like Figure 7-6.

Figure 7-6

MySQL Monitor on a UNIX platform

CHAPTER 7

Although the

screen cap-

tures in this

chapter are

taken from a

UNIX operating system

console window, the

MySQL Monitor portion of

your window should

appear the same regard-

less of which operating

system you use.

Working with Databases and MySQL

394

When you finish working with MySQL Monitor, you can log out and

exit the program by entering either the exit or quit command. You

are successfully logged out when you see “Bye” and your command

prompt is restored to the command line for your operating system.

The following example shows how the command line appears on a

Windows installation of MySQL:

mysql> exit[ENTER ]

Bye

[dongosselin] $

To log out of MySQL Monitor:

1.

2.

Return to MySQL Monitor.

Type exit or quit and press Enter. You should see “Bye”

printed to the screen and the command prompt restored to

the command line for your operating system.

Working with MySQL Monitor

The mysql> command prompt in MySQL Monitor is where most

of the action occurs when you create or manipulate databases in

MySQL. If you are familiar with graphical database management

systems, such as Microsoft Access, you might need some time to get

used to the mysql> command prompt. However, keep in mind that

most database management systems, including Access, use SQL to

manipulate databases. MySQL just removes the graphical “front end”

and allows you to enter SQL commands directly. After you become

familiar with working in MySQL Monitor, you may find that you

prefer manipulating databases with the mysql> command prompt

over using a graphical DBMS because you have more precise con-

trol over your database. You may also find that a graphical front end

might not always be available for the database that you need to use,

so your only option is to use a command-line utility. It’s also worth

repeating that you must understand how to write SQL commands

manually to access MySQL databases from PHP scripts, as you do in

the next chapter.

When you enter a SQL command at the mysql> command prompt,

you must terminate the command with a semicolon. For example, the

following SQL statement lists all of the databases currently defined

for your user name:


Getting Started with MySQL

MYSQL> SHOW DATABASES;[ENTER ]

+-------------+

| Database|

+-------------+

| dongosselin |

| mysql|

| test|

+-------------+

3 rows in set (0.00 sec)

mysql>

You can use

the up and

down arrow

keys on the

keyboard to

scroll back through previ-

ously entered commands.

Once the command is

selected, you can edit it.

Be sure that the cursor is

at the end of the com-

mand before pressing the

Enter key, or anything

after the insertion point

will be ignored.

395

If you omit the ending semicolon when you enter a SQL statement,

MySQL Monitor assumes that you want to enter a multiple-line

command and changes the prompt to ->, which indicates that you

need to enter the next line of the command. For example, the follow-

ing version of the SHOW command does not include the terminating

semicolon. For this reason, the command prompt changes to -> so

that you can enter more statements.

mysql> SHOW DATABASES[ENTER ]

->

To finish executing the preceding statement, just type a semicolon by

itself at the -> command prompt and press Enter.

The SQL keywords you enter in MySQL Monitor are not case

sensitive, so you can enter any of the following statements to list the

databases available to you:

mysql> SHOW databases;[ENTER ]

mysql> show databases;[ENTER ]

mysql> SHOW DATABASES;[ENTER ]

Although you can use any case for SQL keywords, most programmers

follow the convention of using uppercase letters for SQL keywords

and using lowercase or mixed case for the names of databases, tables,

and fields.

Understanding MySQL Identifiers

In MySQL, you must define identifiers (names) for databases, tables,

fields, indexes, and aliases. An alias is an alternate name that you

can use to refer to a table or field in SQL statements. In MySQL, all

identifiers except aliases are limited to 64 characters in length. Aliases

can be up to 255 characters. For database and table names, you can

include any characters that your operating system allows in directory

names and filenames, with the exception of forward slashes (/), back-

slashes (\), and periods (.). Fields, indexes, and aliases can consist of

any characters, including forward slashes, backslashes, and periods.


CHAPTER 7

Working with Databases and MySQL

Identifiers in MySQL are quoted using the backtick, or left single

quote, character ('). Any identifier may be enclosed in backticks, but

certain identifiers must be enclosed in backticks. The following list

shows when an identifier must be quoted.

396

• An identifier that includes any character except standard alphanu-

meric characters, underscores (_), or dollar signs ($)

• An identifier that contains one or more space characters

• An identifier that is a reserved word in MySQL

Many other

DBMSs do

not allow

special char-

acters such

as the space in identi-

fiers, nor do they allow

identifiers to start with a

digit. To allow for portabil-

ity across systems, many

programmers specify

identifiers using the most

common naming conven-

tion, which uses a letter

for the first character,

followed only by letters,

numbers, and the under-

score (_) character.

• An identifier made entirely of numeric digits

• An identifier that contains a backtick character

As shown in the preceding list, an identifier must be enclosed in

backtick characters for the identifier to contain a backtick character.

Additionally, the backtick character within the identifier must be

escaped by preceding it with a backtick character. For example, the

identifier don't must be encoded as 'don''t'.

For example, if the first name and last name fields in the

Employees table include spaces, you must use backticks to refer to

the fields. The following statement demonstrates how to return the

first name and last name fields from the Employees table:

mysql> SELECT * 'first name', 'last name' FROM Employees[ENTER ]

-> WHERE city = "Spencer" ORDER BY 'last name', 'first

name';[ENTER ]

Field and

index identi-

fiers are

case insensi-

tive on all

platforms.

Even though SQL keywords are not case sensitive, the case sensitivity

of database and table identifiers depends on your operating system.

MySQL stores each database in a directory of the same name as the

database identifier. Tables are stored in the database directory in files

of the same name as the table identifier. Directory names and file-

names are not case sensitive on Windows platforms, but are case sen-

sitive on UNIX/Linux systems. This means that you do not need to

worry about case sensitivity in database and table names on Windows

platforms, but you do need to observe letter case when referring to

database and table names on UNIX/Linux systems.

Getting Help with MySQL Commands

Most of the commands you enter in MySQL Monitor are SQL com-

mands. However, MySQL Monitor includes additional commands,

such as exit and quit, which are not part of the SQL language. If you

type help; or ? at the MySQL command prompt, you should see sev-

eral support URLs along with the following command descriptions

shown in Table 7-2:


Getting Started with MySQL

Short

Form

\?

\c

\r

\d

\e

\G

\q

\g

\n

\h

\t

\P

\p

\R

\q

\#

\.

\s

\!

\T

\u

Command

?

clear

connect

delimiter

edit

ego

exit

go

nopager

help

note

pager

print

prompt

quit

rehash

source

status

system

tee

use

Description

Synonym for “help”

Clear command

Reconnect to the server. Optional arguments are db and host.

Set query delimiter

Edit command with $EDITOR

Send command to MySQL server and display result vertically

Exit MySQL. Same as quit.

Send command to MySQL server

Disable pager, print to stdout

Display this help

Don’t write into outfile

Set PAGER [to_pager]. Print the query results via PAGER.

Print current command

Change your MySQL prompt

Quit MySQL

Rebuild completion hash

Execute a SQL script file. Takes a filename as an argument.

Get status information from the server

Execute a system shell command

Set outfile [to_outfile]. Append everything into given outfile.

Use another database. Takes database name as argument.

397

Table 7-2

List of common MySQL commands

Each of the preceding commands has a long and a short form. The

long form of each command is not case sensitive, so you can use any

case you want. (For example, QUIT and Quit are both acceptable.)

However, for the sake of consistency, you should stick with the letter

cases that are presented in this book for each command. The short

form of each command allows you to type a backslash and a single

character to execute the command. Unlike each command’s long

form, the short form is case sensitive. To enter the short form of the

quit command, for example, you must use \q, not \Q. With both the

long and short forms of each command, you can include a semicolon

to terminate the line, although it is not required.

The edit,

nopager,

pager, and

system

commands

are only

available on UNIX/Linux

systems.


CHAPTER 7

Working with Databases and MySQL

To log back in to MySQL Monitor and display help for the MySQL

Monitor commands:

1.

Return to your console window and log back in to MySQL

with the root account, or with the user name and password

supplied by your ISP or instructor.

Type help; or ? at the MySQL command prompt and press

Enter. You should see a list of MySQL commands, as shown

in Figure 7-7.

Log out by typing \q at the MySQL command prompt and

pressing Enter. You should see “Bye” displayed on the screen

and the command prompt restored to the command line for

your operating system.

398

2.

3.

Figure 7-7

MySQL command help

Short Quiz

1.

2.

3.

What is the termination character for a SQL statement?

What SQL command(s) log you out of MySQL Monitor?

Explain how a multiline SQL statement is structured in

MySQL Monitor.

How can you browse through previous SQL commands in

MySQL Monitor?

4.

Working with MySQL Databases

Working with MySQL Databases

This section explains the basics of working with databases in MySQL.

Creating Databases

You use the CREATE DATABASE statement to create a new database.

The following statement creates the vehicle_fleet database:

mysql> CREATE DATABASE vehicle_fleet;[ENTER ]

Query OK, 1 row affected (0.00 sec)

399

If the database is created successfully, you see the “Query OK” mes-

sage shown in the preceding example. If the database already exists,

you see the following message:

mysql> CREATE DATABASE vehicle_fleet;[ENTER ]

ERROR 1007: Can't create database 'vehicle_fleet';

database exists

To use a specific database, you must select it by executing the

USE database statement, as follows:

mysql> USE vehicle_fleet;[ENTER ]

Database changed

You see the “Database changed” message if MySQL successfully

changes to the specified database. User accounts that do not have

permission to work with a specified database receive an error mes-

sage similar to the following:

mysql> USE vehicle_fleet;[ENTER ]

ERROR 1044: Access denied for user 'dongosselin'@'%' to

database 'vehicle_fleet'

You will

study how to

manage user

accounts

and permis-

sions later in this chapter.

Creating a new database does not automatically make the new database

the active database. You must follow the CREATE DATABASE command

with a USE database command to use the newly created database.

To verify that you are in the correct database, you use the MySQL

built-in function DATABASE(). The DATABASE() function returns the

name of the currently active database. Unlike PHP, when you call a

function in MySQL, you must use the SELECT keyword before the

function. This tells MySQL to execute the function and return the

result. To verify that you are using the vehicle_fleet database, you

would enter the following:

mysql> SELECT DATABASE();[ENTER ]

Keep in mind that the CREATE DATABASE statement only creates a new

directory for the specified database. Before you can add records to a

new database, you must first define the tables and fields that will store

your data. Later in this chapter, you will learn how to define tables

and fields in a database.


CHAPTER 7

Working with Databases and MySQL

To create a new database:

1.

Return to MySQL Monitor. You should still be logged in from

the preceding exercise.

Enter the following command to create the sitevisitors

database:

mysql> CREATE DATABASE sitevisitors;[ENTER ]

2.

400

3.

After you see the “Query OK” message, enter the following

command to select the sitevisitors database:

mysql> USE sitevisitors;[ENTER ]

4.

If you install

a local ver-

sion of

MySQL, two

databases

are installed with it:

mysql and test. The

mysql database con-

tains user accounts and

other information required

for your installation of the

MySQL database server.

The test database

ensures that the data-

base server is working

properly.

After you see the “Database changed” message, type

the following command to ensure that you selected the

sitevisitors database:

mysql> SELECT DATABASE();[ENTER ]

Selecting a Database

To view the databases that are available, use the SHOW DATABASES

statement shown earlier, as follows:

mysql> SHOW DATABASES;[ENTER ]

+---------------+

| Database|

+---------------+

| vehicle_fleet |

+---------------+

1 row in set (0.00 sec)

No database is selected when you first log in to MySQL. To work with

a database, you must first select it by executing the USE database

statement, just as you did after creating the database. For example,

the following statement selects the vehicle_fleet database:

mysql> USE vehicle_fleet;[ENTER ]

Database changed

If you forget which database is selected, you can use the

SELECT DATABASE() statement to display the name of the currently

selected database, as follows:

mysql> SELECT DATABASE();[ENTER ]

+---------------+

| DATABASE()|

+---------------+

| vehicle_fleet |

+---------------+

1 row in set (0.00 sec)

The response from the SELECT DATABASE(); command shows that

you are in the vehicle_fleet database.


Working with MySQL Databases

To log back in to MySQL Monitor and select a database:

1.

Return to your console window and log back in to MySQL

with the root account or with the user name and password

supplied by your ISP or instructor.

Type the following command to display the databases that are

available in your MySQL installation. By default, you should

only see the mysql and test databases, although your installa-

tion might include more.

mysql> SHOW DATABASES;[ENTER ]

2.

401

3.

Type the following at the MySQL command prompt to select

the mysql database:

mysql> USE mysql;[ENTER ]

4.

After you see the “Database changed” message, type the follow-

ing command to ensure that you selected the mysql database:

mysql> SELECT DATABASE();[ENTER ]

Your screen should look like Figure 7-8.

Figure 7-8

MySQL Monitor after selecting a database

Deleting Databases

To delete a database, you execute the DROP DATABASE statement,

which removes all tables from the database and deletes the database

itself. The syntax for the DROP DATABASE statement is as follows:

DROP DATABASE database;

CHAPTER 7

Although the

vehicle_

fleet data-

base is

deleted with

this command, it will be

re-created for use with

examples later in this

chapter.

Working with Databases and MySQL

The following statement deletes the vehicle_fleet database:

mysql> DROP DATABASE vehicle_fleet;[ENTER ]

Query OK, 0 rows affected (0.00 sec)

To delete the test database:

1.

2.

402

Return to MySQL Monitor.

Type the following command to ensure that the test database

exists in your MySQL installation:

mysql> SHOW DATABASES;[ENTER ]

You must be

logged in as

the root

user or have

DROP privi-

leges to delete a data-

base. You will study

privileges later in this

chapter.

3.

If you see the test database in the list of available databases,

enter the following command to delete it:

mysql> DROP DATABASE test;[ENTER ]

4.

After you see the “Query OK” message, enter the following com-

mand again to ensure that the test database no longer exists:

mysql> SHOW DATABASES;[ENTER ]

If you are

working with

an instance

of MySQL

that is

hosted by an ISP, the

test database might

have already been

deleted or you might not

have sufficient privileges

to delete databases.

Short Quiz

1.

2.

What statement creates a new directory for a specified database?

What built-in function can be used to return the name of the

active database?

What statement must be executed to change to a specified

database from the active database?

What statement is used to delete a database and any tables it

contains?

3.

4.

Defining Database Tables

This section explains how to select field data types, create tables, and

delete existing tables. Remember that before you can add tables to a

database, you must first create the database, as described earlier in

this chapter.

Specifying Field Data Types

By now, you should thoroughly understand that PHP variables consist

of different data types, which are the specific categories of informa-

tion that a variable can contain. Just like PHP variables, the fields


Defining Database Tables

in a table also store data according to type. Recall that one of the

most important purposes of a variable’s data type is to determine

how much memory the computer allocates for the data stored in the

variable. Similarly, the data types in database fields determine how

much storage space the computer allocates for the data in the data-

base. MySQL includes numerous data types that are categorized into

numeric types, string types, and date/time types. Table 7-3 lists some

of the common MySQL data types.

403

Type

BOOL

TINYINT

SMALLINT

MEDIUMINT

INT or

INTEGER

BIGINT

FLOAT

Storage

1 byte

1 byte

2 bytes

3 bytes

4 bytes

8 bytes

4 bytes

Range

–128 to 127

–128 to 127

–32,768 to 32,767

–8,388,608 to 8,388,607

–2,147,483,648 to 2,147,483,647

–9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

–3.402823466E+38 to

–1.175494351E-38, 0,

and 1.175494351E-38 to

3.402823466E+38

–1.7976931348623157E+308 to

–2.2250738585072014E-308, 0,

and 2.2250738585072014E-308 to

1.7976931348623157E+308

‘0000-00-00’, ‘1000-01-01’ to

‘9999-12-31’

‘–838:59:59’ to ‘838:59:59’

Fixed-length string between 0 to

255 characters

Variable-length string with a maximum

length between 0 to 65,535

characters

One of a set of predefined strings

Zero or more of a set of predefined

strings, separated by commas

Special information

0 is considered FALSE

0 to 24 bits of precision

DOUBLE or

DOUBLE

PRECISION

DATE

TIME

CHAR (m)

VARCHAR (m)

8 bytes

25-53 bits of precision

3 bytes

3 bytes

Number of bytes

specified by m

Varies up to the

number of bytes

specified by m

Varies

Varies

Maximum length is 255 in

older versions

ENUM

SET

Table 7-3

Common MySQL data types


CHAPTER 7

You can find

a complete

listing of

MySQL data

types in the

MySQL Reference Manual

at http://dev.mysql.com/

doc/mysql/en/index.html.

Working with Databases and MySQL

404

To store text

in a field,

you specify

a data type

of CHAR(m)

or VARCHAR(m). For

both data types, you

replace m with the maxi-

mum number of charac-

ters you anticipate the

field will store. In general,

you should use the

VARCHAR(m) data type

because the amount of

storage space it occupies

varies according to the

number of characters in

the field.

Be sure you

have exe-

cuted the

USE state-

ment to

select a database before

executing the

CREATE TABLE state-

ment, or you might cre-

ate your new table in the

wrong database.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]