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

Ifies the table being changed and the change to make.

• To delete a table, you execute the

DROP TABLE statement, which

removes all data and the table definition.

• You use a

GRANT statement to create user accounts and assign

privileges, which refer to the operations that a user can perform

with a database.

• You use the

REVOKE statement to take away privileges from an

existing user account for a specified table or database.

• You add individual records to a table with the

INSERT statement.

• To add multiple records to a database, you use the

LOAD DATA

statement with a local text file that contains the records you want

to add.

• You use the

SELECT statement to retrieve records from a table.

Comprehension Check

• You use the

ORDER BY keyword with the SELECT statement to per-

form an alphanumeric sort of the results returned from a query. To

perform a reverse sort, add the DESC keyword after the name of the

field by which you want to perform the sort.

• You can specify which records to return from a database by using

the WHERE keyword.

• You use the

UPDATE statement to update records in a table.

• You use the

DELETE statement to delete records from a table.

• The phpMyAdmin graphical tool simplifies the tasks associated

with creating and maintaining databases and tables.

435

Comprehension Check

1.

2.

3.

A flat-file database consists of a single table. True or False?

Explain how relational databases are organized.

What is the correct term for the individual pieces of informa-

tion that are stored in a database record?

a. element

b. field

c. section

d. container

4.

What is the name of one table’s primary key when it is stored

in another table?

a. key symbol

b. record link

c. foreign key

d. unique identifier

5.

Breaking tables into multiple related tables to reduce redun-

dant and duplicate information is called.

a. normalization

b. redundancy design

c. splitting

d. simplification


CHAPTER 7

Working with Databases and MySQL

6.

Suppose you have a relational database for a dry-cleaning

company. Each customer of the company can have multiple

items in a cleaning order. What type of relationship exists

between the order and the items?

a. one-to-one

436

b. one-to-many

c. many-to-one

d. many-to-many

7.

has become the standard data manipulation

language among many database management systems.

a. Java

b. SQL

c. ASP.NET

d. PERL

8.

Files created by different database management systems are

completely interchangeable. True or False?

What is the default value of the mysql command’s -h

argument?

a. database

b. mysqlmonitor

c. mysqladmin

d. localhost

10. What character must terminate SQL commands in MySQL

Monitor?

a. colon (:)

b. semicolon (;)

c. ampersand (&)

d. period (.)

9.


Comprehension Check

11. With what characters do you quote identifiers that include

special characters?

a. quotation marks (')

b. double quotation marks (")

c. backticks (')

d. tildes (~)

12. SQL keywords are case sensitive in MySQL Monitor.

True or False?

13. Explain case sensitivity issues for file and directory names.

14. Which of the following statements displays the available

databases in your MySQL installation?

a. SHOW DATABASES;

b. SHOW DATABASES();

c. LIST FILES;

d. GET LIST();

15. What’s the first thing you should do after creating a new

database?

a. Save the database.

b. Restart MySQL Monitor.

c. Select the database.

d. Create a table.

16. Thestatement changes a table named

“visitors” to a table named “guests”.

a. RENAME visitors TO guests;

b. ALTER TABLE CHANGE visitors TO guests;

c. ALTER TABLE visitors RENAME guests;

d. RENAME TABLE visitors guests;

17. A GRANT statement does not create new user accounts.

True or False?

437


CHAPTER 7

Working with Databases and MySQL

18. Explain how to add multiple records to a table using a single

SQL statement.

19. Which of the following keywords causes the ORDER BY clause

to perform a reverse sort of database records?

438

a. DESC

b. REVERSE

c. DESCEND

d. SORTR

20. Which of the following is the correct string for a filter that

narrows a query result to include only records in which the

State field is equal to Massachusetts?

a. WHERE State = 'Massachusetts'

b. State = 'Massachusetts'

c. WHERE 'State' = Massachusetts

d. 'State' = 'Massachusetts'

Reinforcement Exercises

Exercise 7-1

If you do not

have database

creation privi-

leges, skip

steps 1

through 3. If you do not

have the FILE privilege,

skip this exercise.

In this project, you will create a database to contain tables of batting

statistics for major league baseball teams. You will then create a table

named teamstats in the baseball_stats database and add records

to the new table from a file named team_stats.txt in your Projects

directory for Chapter 7.

1.

2.

Log in to MySQL Monitor with your root account or with the

user name and password supplied by your ISP or instructor.

Enter the following command to create a database named

baseball_stats:

mysql> CREATE DATABASE baseball_stats;[ENTER ]

3.

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

command to select the baseball_stats database:

mysql> USE baseball_stats;[ENTER ]


Reinforcement Exercises

4.

After you see the “Database changed” message, type

the following command to ensure that you selected the

baseball_stats database:

mysql> SELECT DATABASE();[ENTER ]

5.

Enter the following command to create the teamstats table.

The Team field uses the VARCHAR data type. Eleven of the col-

umns use INT data types, and the remaining two fields use

FLOAT data types. Each of the statistical field names uses com-

mon baseball abbreviations, such as G for games, AB for at-

bats, R for runs, and HR for home runs.

mysql> CREATE TABLE teamstats (Team VARCHAR(50),

FirstYear INT,[ENTER ]

-> G INT, W INT, L INT, Pennants INT, WS INT,[ENTER ]

-> R INT, AB INT, H INT, HR INT, AVG FLOAT,[ENTER ]

-> RA INT, ERA FLOAT);[ENTER ]

439

6.

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

command to display the structure of the new table:

mysql> DESCRIBE teamstats;[ENTER ]

7.

Enter a LOAD DATA statement that inserts records from the

team_stats.txt file in your Projects directory for Chapter 7

into the teamstats table. Replace path_to_PHP_folders with

the full path for your PHP_Projects directory for Chapter 7.

mysql> LOAD DATA INFILE 'path_to_PHP_folders/

Chapter.07/Projects/team_stats.txt'[ENTER ]

-> INTO TABLE teamstats;[ENTER ]

Use the

MySQL serv-

er’s direc-

tory path,

not the Web

URL path.

8.

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

command to view all the records in the teamstats table:

mysql> SELECT * FROM teamstats;[ENTER ]

Exercise 7-2

In this project, you will write SQL statements that return team

names, games played, and number of at-bats from the teamstats

table in the baseball_stats database. You will also write SQL state-

ments that return the teams that have the least and most all-time

home runs. For these select queries, you will need to use the LIMIT

keyword, which restricts the number of records returned from the

database. For example, if you specify a value of 10 with the LIMIT

keyword, the database returns the first 10 records that match the con-

ditions of your query. Finally, you will write SQL statements that use

the SUM() function to return the total number of games played by all


CHAPTER 7

Working with Databases and MySQL

teams and the AVG() function to return the common batting average

for all teams.

1.

2.

440

Return to MySQL Monitor.

Enter the following SELECT statement, which returns the team,

G (games played), and AB (at bats) fields from the teamstats

table:

mysql> SELECT team, G, AB FROM teamstats;[ENTER ]

3.

Enter the following SELECT statement, which returns the team,

G (games played), and AB (at bats) fields from the teamstats

table, sorted by team name:

mysql> SELECT team, G, AB FROM teamstats ORDER BY

team;[ENTER ]

4.

Enter the following SELECT statement, which returns the team,

G (games played), and AB (at bats) fields from the teamstats

table, reverse sorted by team name:

mysql> SELECT team, G, AB FROM teamstats ORDER BY

team DESC;[ENTER ]

5.

Enter the following SELECT statement, which returns the team

and HR (home runs) fields. The statement sorts the records by

the HR field and includes the LIMIT keyword, assigned a value

of 1. Because the records are sorted in ascending order, the

statement returns the first record, which lists the team with

the least all-time home runs: the Tampa Bay Rays, with 1713.

mysql> SELECT team, HR FROM teamstats ORDER BY HR

LIMIT 1;[ENTER ]

6.

Enter the following SELECT statement, which also returns

the team and HR (home runs) fields. The statement reverse

sorts the records by the HR field and includes the LIMIT key-

word, assigned a value of 1. Because the records are sorted

in descending order, the statement returns the first record,

which lists the team with the most all-time home runs: the

New York Yankees, with 13,914.

mysql> SELECT team, HR FROM teamstats ORDER BY HR

DESC LIMIT 1;[ENTER ]

7.

Enter the following SELECT statement, which uses the SUM()

function to return the total number of games played by sum-

ming the contents of the G fields. Because each game played

was between two teams in the database, the sum will be twice

the actual number of games, so you divide the result by two.

You should see a value of 182,525.

mysql> SELECT SUM(G)/2 FROM teamstats;[ENTER ]

Reinforcement Exercises

8.

Enter the following SELECT statement, which uses the AVG()

function to return the batting average for all teams by averag-

ing the contents of the AVG fields. You should see a value of

0.26199999650319.

mysql> SELECT AVG(AVG) FROM teamstats;[ENTER ]

9.

Unfortunately, this is not the true all-time batting average,

because each team has a different number of at-bats. Enter

the following SELECT statement, which gets the weighted

average per team, and divides by the total number of at-bats.

You should see a value of 0.26256022536176.

mysql> SELECT SUM(AVG*AB)/SUM(AB) FROM

teamstats;[ENTER ]

441

Exercise 7-3

In this project, you will add a new table for home run leaders to the

baseball_stats database. Before you create the new table, you will

create a text file using data from the teamstats table. You will then

import the data from the text file into MySQL to create a new table

named hrleaders. To create the home run leaders table, you will use

the INTO OUTFILE clause with a SELECT statement. The INTO OUTFILE

clause copies the returned records into a specified file. You will use

the FIELDS TERMINATED BY and LINES TERMINATED BY clauses

to specify how the text file should be structured. Because you will

import the home run records into the new table, you separate each

field with a tab and each line with a line break. If you do not have the

FILE privilege, skip this exercise.

1.

2.

Return to MySQL Monitor.

Enter the following SQL statement, which returns the team

and HR fields for the teams with the highest number of home

runs. Replace path_to_PHP_folders with the full path for

your PHP_Projects directory for Chapter 7. Notice that the

statement uses the ORDER BY and DESC keywords to perform

a reverse sort of the fields. The results are sent to a text file

named hrleaders.txt, with each field separated by a tab and

each line separated by a line break escape sequence (\n).

mysql> SELECT team, HR FROM teamstats[ENTER ]

-> ORDER BY HR DESC LIMIT 10[ENTER ]

-> INTO OUTFILE 'path_to_PHP_folders/Chapter.07/

Projects/hrleaders.txt'[ENTER ]

-> FIELDS TERMINATED BY '\t'[ENTER ]

-> LINES TERMINATED BY '\n';[ENTER ]

An error code

of 13 indi-

cates that you

do not have

write privi-

leges to the destination

directory.

Use the

MySQL serv-

er’s direc-

tory path,

not the Web

URL path.


CHAPTER 7

Working with Databases and MySQL

3.

Enter the following command to create a table named

hrleaders:

mysql> CREATE TABLE hrleaders (Team VARCHAR(50), HR

INT);[ENTER ]

4.

442

Use the

MySQL serv-

er’s direc-

tory path,

not the Web

URL path.

Enter the following LOAD DATA statement to import records

from the hrleaders.txt file into the hrleaders table.

Replace path_to_PHP_folders with the full path for your

PHP_Projects directory for Chapter 7.

mysql> LOAD DATA INFILE 'path_to_PHP_folders/

Chapter.07/Projects/hrleaders.txt'[ENTER ]

-> INTO TABLE hrleaders;[ENTER ]

5.

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

command to view all the records in the hrleaders table:

mysql> SELECT * FROM hrleaders;[ENTER ]

6.

Finally, enter the following command to list the tables in the

baseball_stats database. You should see the hrleaders and

teamstats tables listed.

mysql> SHOW TABLES;[ENTER ]

7.

Exit from MySQL Monitor.

Exercise 7-4

Create a demographics database with a table that contains the fol-

lowing fields: country, primary language, and population. Enter

records for at least 10 countries. You can find demographic informa-

tion for various countries in many places on the Internet, including

Wikipedia (http://www.wikipedia.org/). Write queries that return the

following:

• A list of all records sorted by country name

• The country with the highest population

• The country with the lowest population

• Countries that share a common language, such as French

Exercise 7-5

Database design techniques include the ability to identify and design

five normalization levels: first normal form through fifth normal

form. Search the Internet or visit your local library for information on

these techniques and describe how to identify and design each nor-

malization level.


Discovery Projects

Discovery Projects

The Chinese Zodiac site is a comprehensive project that will be

updated in the Discovery Projects in each chapter. All files for the

Chinese Zodiac site will be saved in a folder named ChineseZodiac

in the root Web folder on the server, and all database tables will be

stored in the chinese_zodiac database.

443

Discovery Project 7-1

In this project, you will create a database named chinese_zodiac

that will contain the tables for the Chinese zodiac. You will then

create a table named zodiacsigns in the chinese_zodiac database

and add records to the new table manually using INSERT statements.

The zodiacsigns table will contain the defining information about

each sign. At this point, the example is very simple, but it will be built

upon as needed.

1.

2.

Log in to MySQL Monitor with your root account or with the

user name and password supplied by your ISP or instructor.

Enter the following command to create a database named

chinese_zodiac:

mysql> CREATE DATABASE chinese_zodiac;[ENTER ]

If you do not

have database

creation privi-

leges, skip

steps 1

through 3.

3.

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

command to select the chinese_zodiac database:

mysql> USE chinese_zodiac;[ENTER ]

4.

After you see the “Database changed” message, type

the following command to ensure that you selected the

chinese_zodiac database:

mysql> SELECT DATABASE();[ENTER ]

5.

Enter the following command to create the zodiacsigns

table. Both fields use the VARCHAR data type.

mysql> CREATE TABLE zodiacsigns (Sign

VARCHAR(10),[ENTER ]

-> President VARCHAR(75));[ENTER ]

6.

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

command to display the structure of the new table:

mysql> DESCRIBE zodiacsigns;[ENTER ]


CHAPTER 7

Working with Databases and MySQL

7.

Use one or more INSERT statements to add records to the

zodiacsigns table for each of the 12 signs of the Chinese

zodiac. The values used to populate the fields come from

Discovery Project 6-4.

For example, the following command will insert the appropri-

ate values for the Rat:

mysql> INSERT INTO zodiacsigns (Sign, President) [ENTER ]

-> VALUES ('Rat', 'George Washington'); [ENTER ]

444

8.

After you have successfully entered information for all

12 signs, enter the following command to view all the records

in the zodiacsigns table:

mysql> SELECT * FROM zodiacsigns;[ENTER ]

Discovery Project 7-2

In this project, you will create a table named zodiacfeedback in the

chinese_zodiac database. This table will be used later to store user

feedback about the Chinese Zodiac site.

1.

2.

Reopen MySQL Monitor.

Type the following command to ensure that you selected the

chinese_zodiac database:

mysql> SELECT DATABASE();[ENTER ]

3.

Enter the following command to create the zodiacfeedback

table. The message_date field is of type DATE and the

message_time field is of type TIME. The sender and message

fields are of type VARCHAR. The public_message field is of a

new type called ENUM. The ENUM type requires that the field

only be populated with values specified in the CREATE TABLE

or ALTER TABLE statement that created the field. In this case,

the public_message field can only contain the values “Y” for

yes and “N” for no.

mysql> CREATE TABLE zodiacfeedback (message_date

DATE,[ENTER ]

-> message_time TIME, sender VARCHAR(40),[ENTER ]

-> message VARCHAR(250), public_message

ENUM('Y','N'));[ENTER ]

4.

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

command to display the structure of the new table:

mysql> DESCRIBE zodiacfeedback;[ENTER ]


Discovery Projects

Discovery Project 7-3

Log in to MySQL Monitor. At the SQL command prompt, select the

chinese_zodiac database. Enter the SQL statement to create a table

named zodiacyears to store the years for each sign of the Chinese

zodiac. The table should have two fields: the year and the name of the

sign for that year.

Enter the SQL command to view the structure of the new table.

Capture an image of the display and save the image as a file named

DP7-3.ext (replacing the .ext with the appropriate extension

for the image type). Upload the file to the Images folder in the

ChineseZodiac directory on the server.

445

Discovery Project 7-4

Create a tab-delimited text file that lists the years and signs, one year

per line, for the Chinese zodiac. For the years and the corresponding

signs, refer to the display generated by Chinese_Zodiac_for_loop.php

from Discovery Project 2-4 and Chinese_Zodiac_while_loop.php from

Discovery Project 2-5. Save the text file as zodiac_years.txt and upload

the file to the ChineseZodiac directory in the root Web folder on the

server.

Enter the SQL statement to populate the zodiacyears table with

the contents of the zodiac_years.txt file. Query the table and sort the

results, first by sign and then by year.

Discovery Project 7-5

Create a table called randomproverb to store the proverbs from

Discovery Project 5-5. The table should have a proverb_number field

of type INT, a proverb field of type VARCHAR of at least 100 characters,

and a display_count field to track the number of times each proverb

is displayed.

Copy the proverbs.txt file (which you created in Discovery

Project 5-5) from the ChineseZodiac directory to a file called prov-

erb_load.txt and open it in your editor. Modify the file so that each

line has a unique numerical index, a tab, the proverb, another tab, and

a zero (for the count). Save and upload the file, then import the file

into the randomproverb table using MySQL Monitor.

You will

modify inc_

footer.php to

use this

table in

Discovery Project 8-5.


CHAPTER

Manipulating MySQL

Databases with PHP

In this chapter, you will:

Connect to MySQL from PHP

Work with MySQL databases using PHP

Create, modify, and delete MySQL tables with PHP

Use PHP to manipulate MySQL records

Use PHP to retrieve database records

8

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