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

Various types of actions, depending on the type of query.

• The

mysql_fetch_row() function returns the fields in the cur-

rent row of a resultset into an indexed array and moves the result

pointer to the next row.

• The

mysql_fetch_assoc() function returns the fields in the cur-

rent row of a resultset into an associative array and moves the

result pointer to the next row.

• The

mysql_free_result() function closes a resultset.

• The

mysql_num_rows() function returns the number of rows in

a query result, and the mysql_num_fields() function returns the

number of fields in a query result.

483

Comprehension Check

1.

Which of the following functions opens a database connection?

a. open()

b. mysql_open()

c. openConnection()

d. mysql_connect()


CHAPTER 8

Manipulating MySQL Databases with PHP

2.

Which of the following functions closes a database

connection?

a. close()

b. mysql_close()

484

c. mysql_free()

d. mysql_free_connect()

3.

To which of the following functions do you need to pass a

variable representing the database connection? (Choose all

that apply.)

a. mysql_get_client_info()

b. mysql_get_host_info()

c. mysql_get_proto_info()

d. mysql_get_server_info()

4.

Which of the following functions terminates script execution?

(Choose all that apply.)

a. exit()

b. bye()

c. die()

d. quit()

5.

Describe three types of errors that can occur when accessing

MySQL databases and other types of data sources with PHP.

The following code structure prevents MySQL error messages

from being displayed if the database connection is not avail-

able. True or False?

$DBConnect = mysql_connect("localhost", "dongosselin",

"rosebud");

if (!$DBConnect)

echo "<p>The database server is not available.</p>";

else {

echo "<p>Successfully connected to the database

server.</p>";

mysql_close($DBConnect);

}

6.


Comprehension Check

7.

Which of the following functions reports the error message

from the last failed database connection attempt?

a. mysql_errmsg()

b. mysql_error_msg()

c. mysql_errno()

d. mysql_error()

485

8.

Which of the following characters suppresses error messages

in PHP?

a. *

b. &

c. #

d. @

9.

What is the correct syntax for selecting a database with the

mysql_select_db() function? (Select all that apply.)

a. mysql_select_db(connection)

b. mysql_select_db(database)

c. mysql_select_db(database, connection)

d. database = mysql_select_db(connection)

10. Write a simple code segment that demonstrates how to use a

mysql_query() function to prevent your code from attempt-

ing to create a table that already exists.

11. Explain what a result pointer is and how to create and use one.

12. Which of the following SQL keywords creates an auto-

incrementing field?

a. AUTO

b. INCREMENT

c. AUTO_INCREMENT

d. AUTOINCREMENT


CHAPTER 8

Manipulating MySQL Databases with PHP

13. Which of the following statements is used to create a query

string in

$SQLstring to delete the company_cars table?

a. $SQLstring = "DELETE TABLE company_cars";

b. $SQLstring = "DROP TABLE company_cars";

486

c. $SQLstring = "REMOVE TABLE company_cars";

d. $SQLstring = "CANCEL TABLE company_cars";

14. When using the INSERT and VALUE keywords to add records

to a table using the

mysql_query() function, what keyword is

used to indicate that there is no value for a field?

15. Which of the following functions returns the number of rows

affected by queries that do not return results, such as

INSERT,

UPDATE, and DELETE queries?

a. mysql_affected_rows()

b. mysql_rows()

c. mysql_get_changed()

d. mysql_fetch_rows()

16. Thefunction returns the number of opera-

tions for various types of actions, depending on the type of

query.

a. mysql_get_info()

b. mysql_operations()

c. mysql_info()

d. mysql_num_rows()

17. Which of the following functions returns the fields in the

current row of a resultset into an indexed array? (Select all

that apply.)

a. mysql_fetch_data()

b. mysql_fetch_array()

c. mysql_index_row()

d. mysql_fetch_row()


Reinforcement Exercises

18. Which of the following functions returns the fields in the

current row of a resultset into an associative array?

a. mysql_assoc_fetch()

b. mysql_fetch_keys()

c. mysql_fetch_assoc()

d. mysql_fetch_index()

19. Which of the following functions closes a resultset to ensure

that it doesn’t keep taking up space in your Web server’s

memory?

a. mysql_free_result()

b. mysql_result_close()

c. mysql_free()

d. mysql_close_result()

20. Write a simple code segment that demonstrates how to use

the

mysql_num_rows() and mysql_num_fields() functions to

determine whether a SQL query returned results.

487

Reinforcement Exercises

Exercise 8-1

In this project, you will create a Web page that allows visitors to your

site to sign a guest book that is saved to a database.

1.

Create a new document in your text editor and type the

<!DOCTYPE> declaration, <html> element, document head, and

<body> element. Use the strict DTD and “Guest Book” as the

content of the <title> element.

Add the following text and elements to the document body:

<h2>Enter your name to sign our guest book</h2>

<form method="POST" action="SignGuestBook.php">

<p>First Name <input type="text" name="first_name"

/></p>

<p>Last Name <input type="text" name="last_name"

/></p>

<p><input type="submit" value="Submit" /></p>

</form>

2.


CHAPTER 8

Manipulating MySQL Databases with PHP

3.

Save the document as GuestBook.html in the Projects

directory for Chapter 8.

Create a new document in your text editor and type the

<!DOCTYPE> declaration, <html> element, document head, and

<body> element. Use the strict DTD and “Sign Guest Book” as

the content of the <title> element.

Add the following script section to the document body:

<?php

?>

4.

488

5.

6.

Add the following statements to the script section to ensure

that visitors enter their first and last names:

if (empty($_POST['first_name']) || empty($_

POST['last_name']))

echo "<p>You must enter your first and last

name! Click your browser's Back button to

return to the Guest Book form.</p>";

7.

Add the following statement to the script section to connect

to the database. Replace host with the host name of your

MySQL server, and user and password with the MySQL user

name and password you created in Chapter 7.

else {

$DBConnect = @mysql_connect("host", "user",

"password");

if ($DBConnect === FALSE)

echo "<p>Unable to connect to the database

server.</p>"

. "<p>Error code " . mysql_errno()

. ": " . mysql_error() . "</p>";

8.

Add the following statements to the end of the script section

to create a database named guestbook if it does not already

exist:

else {

$DBName = "guestbook";

if (!@mysql_select_db($DBName, $DBConnect)) {

$SQLstring = "CREATE DATABASE $DBName";

$QueryResult = @mysql_query($SQLstring,

$DBConnect);

if ($QueryResult === FALSE)

echo "<p>Unable to execute the

query.</p>"

. "<p>Error code " . mysql_

errno($DBConnect)

. ": " . mysql_error($DBConnect)

. "</p>";


Reinforcement Exercises

else

echo "<p>You are the first

visitor!</p>";

}

mysql_select_db($DBName, $DBConnect);

9.

Add the following statements to the end of the script section

to create a table named count if it does not already exist. The

table consists of a single auto-incrementing primary key field

named countID.

$TableName = "visitors";

$SQLstring = "SHOW TABLES LIKE '$TableName'";

$QueryResult = @mysql_query($SQLstring, $DBConnect);

if (mysql_num_rows($QueryResult) == 0) {

$SQLstring = "CREATE TABLE $TableName

(countID SMALLINT

NOT NULL AUTO_INCREMENT PRIMARY KEY,

last_name VARCHAR(40), first_name VARCHAR(40))";

$QueryResult = @mysql_query($SQLstring,

$DBConnect);

if ($QueryResult === FALSE)

echo "<p>Unable to create the table.</p>"

. "<p>Error code " . mysql_

errno($DBConnect)

. ": " . mysql_error($DBConnect) .

"</p>";

489

10.

Finally, add the following statements to the end of the script

section. These mysql_query() statements add the visitor to the

database. The last statement closes the database connection.

$LastName = stripslashes($_

POST['last_name']);

$FirstName = stripslashes($_

POST['first_name']);

$SQLstring = "INSERT INTO $TableName

VALUES(NULL, '$LastName',

'$FirstName')";

$QueryResult = @mysql_

query($SQLstring, $DBConnect);

if ($QueryResult === FALSE)

echo "<p>Unable to execute the

query.</p>"

. "<p>Error code " . mysql_

errno($DBConnect)

. ": " . mysql_

error($DBConnect) . "</p>";

else

echo "<h1>Thank you for signing

our guest book!</h1>";

}

mysql_close($DBConnect);

}

}


CHAPTER 8

Manipulating MySQL Databases with PHP

11. Save the document as SignGuestBook.php in the Projects

directory for Chapter 8. Upload both SignGuestBook.php and

GuestBook.html to the server.

12. Open GuestBook.html in your Web browser by entering

the following URL: http://<yourserver>/PHP_Projects/

Chapter.08/Projects/GuestBook.html. Test the form to see if

you can add your name to the database.

13. Close your Web browser window.

490

Exercise 8-2

In this project, you will add a document to the Guest Book program

you created in Reinforcement Exercise 8-1. This document displays

the entries in the guest book.

1.

Create a new document in your text editor and type the

<!DOCTYPE> declaration, <html> element, document head, and

<body> element. Use the strict DTD and “Guest Book Posts”

as the content of the <title> element.

Add the following script section to the document body:

<?php

?>

2.

3.

Add the following statement to the script section to connect

to the database. Replace host with the host name of your

MySQL server, and user and password with the MySQL user

name and password you created in Chapter 7.

$DBConnect = @mysql_connect("host", "user", "password ");

if ($DBConnect === FALSE)

echo "<p>Unable to connect to the database

server.</p>"

. "<p>Error code " . mysql_errno()

. ": " . mysql_error() . "</p>";

4.

Add the following statements to the end of the script section

to connect to the guestbook database. If the database does

not exist, a message reports that the guest book does not con-

tain any entries.

else {

$DBName = "guestbook";

if (!@mysql_select_db($DBName, $DBConnect))

echo "<p>There are no entries in the guest

book!</p>";


Reinforcement Exercises

5.

Add the following statements to the end of the script section

to select all the records in the visitors table. If no records

are returned, a message reports that the guest book does not

contain any entries.

else {

$TableName = "visitors";

$SQLstring = "SELECT * FROM $TableName";

$QueryResult = @mysql_query($SQLstring,

$DBConnect);

if (mysql_num_rows($QueryResult) == 0)

echo "<p>There are no entries in

the guest book!</p>";

491

6.

Add the following statements to the end of the script section

to display the records returned from the visitors table:

else {

echo "<p>The following visitors have

signed our guest book:</p>";

echo "<table width='100%' border='1'>";

echo "<tr><th>First Name</th><th>Last

Name</th></tr>";

while (($Row = mysql_fetch_

assoc($QueryResult)) !== FALSE) {

echo "<tr><td>{$Row['first_

name']}</td>";

echo "<td>{$Row['last_name']}</

td></tr>";

}

7.

Add the following statements to the end of the script section

to close the database connection and the result pointer:

}

mysql_free_result($QueryResult);

}

mysql_close($DBConnect);

}

8.

Save the document as ShowGuestBook.php in the Projects

directory for Chapter 8.

Return to the GuestBook.html document in your text edi-

tor and add the following text and elements to the end of the

document body:

<p><a href="ShowGuestBook.php">Show Guest Book</a></p>

9.


CHAPTER 8

Manipulating MySQL Databases with PHP

10. Save the GuestBook.html file, and then open it in your Web

browser by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.08/Projects/GuestBook.html. Click the

Show Guest Book link to see if the script functions correctly.

492

11. Close your Web browser window.

Exercise 8-3

Create a Web page to be used for storing software development bug

reports in a MySQL database. Include fields such as product name

and version, type of hardware, operating system, frequency of occur-

rence, and proposed solutions. Include links on the main page that

allow you to create a new bug report and update an existing bug

report.

Exercise 8-4

Create a Web site for tracking, documenting, and managing the

process of interviewing candidates for professional positions. On

the main page, include a form with fields for the interviewer’s name,

position, and date of interview. Also include fields for entering the

candidate’s name, communication abilities, professional appearance,

computer skills, business knowledge, and interviewer’s comments.

Clicking the Submit button should save the data in a MySQL data-

base. Include a link for opening a document that displays each candi-

date’s interview information.

Exercise 8-5

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