Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.37 MB, 561 trang )
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
Connecting to MySQL with PHP
To successfully use the PHP functions to talk to MySQL, you must have MySQL running at a location to which your
Web server can connect (not necessarily the same machine as your Web server). You also must have created a user
(with a password), and you must know the name of the database to which you want to connect. If you followed the
instructions in Hour 1, "Installing and Configuring MySQL," and Hour 3, "Installing and Configuring PHP," you
should already have taken care of this.
In all sample scripts in this hour, the sample database name is testDB, the sample user is joeuser, and the sample
password is somepass. Substitute your own information when you use these scripts.
You can find the section of the PHP Manual that covers all MySQL-related functions at
http://www.php.net/manual/en/ref.mysql.php. Use it!
Using mysql_connect()
The mysql_connect() function is the first function you must call when utilizing a PHP script to connect to
MySQL—without an open connection to MySQL, you won't get very far! The basic syntax for the connection is
mysql_connect("hostname", "username", "password");
Using actual sample values, the connection function looks like this:
mysql_connect("localhost", "joeuser", "somepass");
This function returns a connection index if the connection is successful or returns false if the connection fails. Listing
8.1 is a working example of a connection script. It assigns the value of the connection index to a variable called
$conn, then prints the value of $conn as proof of a connection.
Listing 8.1 A Simple Connection Script
1:
2:
3:
4:
$conn = mysql_connect("localhost", "joeuser", "somepass");
echo "$conn";
?>
Save this script as mysqlconnect.php and place it in the document area of your Web server. Access the script with
your Web browser and you will see something like the following in your Web browser:
Resource id #1
Connecting to MySQL using the mysql_connect() function is pretty straightforward. The connection closes when the
script finishes its execution, but if you would like to explicitly close the connection, simply add the mysql_close()
function at the end of the script, as in Listing 8.2.
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
Working with MySQL Data
Inserting, updating, deleting, and retrieving data all revolve around the use of the mysql_query() function to execute
the basic SQL queries. For INSERT, UPDATE, and DELETE, no additional scripting is required after the query has
been executed because you're not displaying any results (unless you want to). For SELECT, you have a few options
for displaying the data retrieved by your query. Let's start with the basics and insert some data, so you'll have
something to retrieve later on.
Inserting Data with PHP
The easiest method for inserting data is to simply hard-code the INSERT statement, as shown in Listing 8.6.
Listing 8.6 A Script to Insert a Record
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
// open the connection
$conn = mysql_connect("localhost", "joeuser", "somepass");
// pick the database to use
mysql_select_db("testDB",$conn);
// create the SQL statement
$sql = "INSERT INTO testTable values ('', 'some value')";
// execute the SQL statement
$result = mysql_query($sql, $conn) or die(mysql_error());
// echo the result identifier
echo $result;
?>
You might wonder why you need to echo the result identifier if you're just inserting data. Well, you don't have to; it's
just there for kicks. You can clean this script up a bit by replacing the query execution line so that it simply executes
and prints a relevant statement if successful, as shown in Listing 8.7.
Listing 8.7 The Modified Insert Script
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
// open the connection
$conn = mysql_connect("localhost", "joeuser", "somepass");
// pick the database to use
mysql_select_db("testDB",$conn);
// create the SQL statement
$sql = "INSERT INTO testTable values ('', 'some value')";
// execute the SQL statement
if (mysql_query($sql, $conn)) {
echo "record added!";
} else {
echo "something went wrong";
}
?>
Running this script will result in the addition of a row to the testTable table. To enter more records than just the one
shown in the script, you can either make a long list of hard-coded SQL statements and use mysql_query() multiple
times to execute these statements, or you can create a form-based interface to the record addition script.
To create the form for this script, you really only need one field because the id field can automatically increment. The
action of the form is the name of the record-addition script; let's call it insert.php. Your HTML form might look
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
Summary
Using PHP and MySQL to create dynamic, database-driven Web sites is a breeze. Just remember that the PHP
functions are essentially a gateway to the database server; anything you'd enter using the MySQL command-line
interface, you can use with mysql_query().
To connect to MySQL with PHP, you need to know your MySQL username, password, and database name. Using
mysql_connect() and mysql_select_db(), you can connect to and select a database to use throughout the life of the
script.
Once connected, you can issue standard SQL commands with the mysql_query() function. If you have issued a
SELECT command, you can use mysql_numrows() to count the records returned in the resultset. If you want to
display the data found, you can use mysql_fetch_array() to get all the results during a loop and display them onscreen.
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
Workshop
The workshop is designed to help you anticipate possible questions, review what you've learned, and begin to put
your knowledge into practice.
Quiz
1:
What is the primary function used to make the
connection between PHP and MySQL, and what
information is necessary?
A1:
The mysql_connect() function creates a connection to
MySQL and requires the hostname, username, and
password.
2:
Which PHP function retrieves a MySQL error
message?
A2:
The mysql_error() function returns a MySQL error
message.
3:
Which PHP function is used to count the number of
records in a resultset?
A3:
The mysql_numrows() function counts the number of
records in a resultset.
Activity
Create a PHP script that displays the contents of the grocery_inventory table that was used in the previous hour.
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
Part III: Getting Involved with
the Code
Hour
9 Working with Forms
10 Working with Files
11 Working with Dates and Times
12 Creating a Simple Calendar
13 Working with Strings
14 Creating a Simple Discussion Forum
15 Restricting Access to Your Applications
16 Working with User Sessions
17 Logging and Monitoring Server Activity
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]
Hour 9. Working with Forms
Until now, the PHP examples in this book have been missing a crucial dimension. Sure, you know the basics, can set
variables and arrays, create and call functions, and connect to MySQL to do great things with a database. But that's
all meaningless if users can't reach into a language's environment to offer it information. In this hour, you look at
strategies for acquiring and working with user input. On the World Wide Web, HTML forms are the principal means
by which substantial amounts of information pass from the user to the server.
In this hour, you will learn
•
How to access information from form fields
•
How to work with form elements that allow multiple selections
•
How to create a single document that contains both an HTML form and the PHP code that handles its
submission
•
How to save state with hidden fields
•
How to redirect the user to a new page
•
How to build HTML forms and PHP code that send mail
•
How to build HTML forms that upload files and how to write the PHP code to handle them
[ Team LiB ]
This document is created with the unregistered version of CHM2PDF Pilot
[ Team LiB ]