Tải bản đầy đủ (.pdf) (10 trang)

Phát triển web với PHP và MySQL - p 27 potx

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 (572.82 KB, 10 trang )

Bear in mind that there is a limit to the number of MySQL connections that can exist at the
same time. The MySQL parameter max_connections determines what this limit is. The pur-
pose of this parameter and the related Apache parameter MaxClients is to tell the server to
reject new connection requests rather than allowing machine resources to be all used at busy
times or when software has crashed.
You can alter both of these parameters from their default values by editing the config-
uration files. To set MaxClients in Apache, edit the httpd.conf file on your system. To set
max_connections for MySQL, edit the file my.conf.
If you use persistent connections and nearly every page in your site involves database access,
you are likely to have a persistent connection open for each Apache process. This can cause a
problem if you leave these parameters set to their default values. By default, Apache allows
150 connections, but MySQL only allows 100. At busy times, there might not be enough con-
nections to go around. Depending on the capabilities of your hardware, you should adjust these
so that each Web server process can have a connection.
Choosing a Database to Use
You will remember that when we are using MySQL from a command line interface, we need
to tell it which database we plan to use with a command such as
use books;
We also need to do this when connecting from the Web. We perform this from PHP with a call
to the mysql_select_db() function, which we have done in this case as follows:
mysql_select_db(“books”);
The mysql_select_db() function has the following prototype:
int mysql_select_db(string database, [int database_connection] );
It will try to use the database called database. You can also optionally include the database link
you would like to perform this operation on (in this case
$db), but if you don’t specify it, the
last opened link will be used. If you don’t have a link open, the default one will be opened as
if you had called mysql_connect().
Querying the Database
To actually perform the query, we can use the mysql_query() function. Before doing this,
however, it’s a good idea to set up the query you want to run:


$query = “select * from books where “.$searchtype.” like ‘%”.$searchterm.”%’”;
Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
235
13 7842 CH10 3/6/01 3:36 PM Page 235
In this case, we are searching for the user-input value ($searchterm) in the field the user speci-
fied ($searchtype). You will notice that we have used like for matching rather than equal—it’s
usually a good idea to be more tolerant in a database search.
Using MySQL
P
ART II
236
It’s important to realize that the query you send to MySQL does not need a semicolon
on the end of it, unlike a query you type into the MySQL monitor.
TIP
We can now run the query:
$result = mysql_query($query);
The mysql_query() function has the following prototype:
int mysql_query(string query, [int database_connection] );
You pass it the query you want to run, and optionally, the database link (again, in this case
$db). If not specified, the function will use the last opened link. If there isn’t one, the function
will open the default one as if you had called mysql_connect().
You might want to use the mysql_db_query() function instead. It has the following prototype:
int mysql_db_query(string database, string query, [int database_connection] );
It’s very similar but allows you to specify which database you would like to run the query on.

It is like a combination of the mysql_select_db() and mysql_query() functions.
Both of these functions return a result identifier (that allows you to retrieve the query results)
on success and false on failure. You should store this (as we have in this case in $result) so
that you can do something useful with it.
Retrieving the Query Results
A variety of functions are available to break the results out of the result identifier in different
ways. The result identifier is the key to accessing the zero, one, or more rows returned by the
query.
In our example, we have used two of these: mysql_numrows() and mysql_fetch_array().
The function mysql_numrows() gives you the number of rows returned by the query. You
should pass it the result identifier, like this:
$num_results = mysql_num_rows($result);
13 7842 CH10 3/6/01 3:36 PM Page 236
It’s useful to know this—if we plan to process or display the results, we know how many there
are and can now loop through them:
for ($i=0; $i <$num_results; $i++)
{
// process results
}
In each iteration of this loop, we are calling mysql_fetch_array(). The loop will not execute
if no rows are returned. This is a function that takes each row from the resultset and returns the
row as an associative array, with each key an attribute name and each value the corresponding
value in the array:
$row = mysql_fetch_array($result);
Given the associative array $row, we can go through each field and display them appropriately,
for example:
echo “<br>ISBN: “;
echo stripslashes($row[“isbn”]);
As previously mentioned, we have called stripslashes() to tidy up the value before display-
ing it.

There are several variations on getting results from a result identifier. Instead of an associative
array, we can retrieve the results in an enumerated array with mysql_fetch_row(), as follows:
$row = mysql_fetch_row($result);
The attribute values will be listed in each of the array values $row[0], $row[1], and so on.
You could also fetch a row into an object with the mysql_fetch_object() function:
$row = mysql_fetch_object($result);
You can then access each of the attributes via $row->title, $row->author, and so on.
Each of these approaches fetches a row at a time. The other approach is to access a field at a
time using mysql_result(). For this, you must specify the row number (from zero to the num-
ber of rows—1) as well as the field name. For example
$row = mysql_result($result, $i, “title”);
You can specify the field name as a string (either in the form “title” or “books.title”) or as
a number (as in mysql_fetch_row()). You shouldn’t mix use of mysql_result() with any of
the other fetching functions.
The row-oriented fetch functions are far more efficient than mysql_result(), so in general
you should use one of those.
Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
237
13 7842 CH10 3/6/01 3:36 PM Page 237
Disconnecting from the Database
You can use
mysql_close(database_connection);
to close a nonpersistent database connection. This isn’t strictly necessary because they will be
closed when a script finishes execution anyway.

Putting New Information in the Database
Inserting new items into the database is remarkably similar to getting items out of the database.
You follow the same basic steps—make a connection, send a query, and check the results. In
this case, the query you send will be an INSERT rather than a SELECT.
Although this is all very similar, it can sometimes be useful to look at an example. In Figure
10.3, you can see a basic HTML form for putting new books into the database.
Using MySQL
P
ART II
238
FIGURE 10.3
This interface for putting new books into the database could be used by Book-O-Rama’s staff.
The HTML for this page is shown in Listing 10.3.
L
ISTING 10.3
newbook.html—HTML for the Book Entry Page
<html>
<head>
<title>Book-O-Rama - New Book Entry</title>
</head>
13 7842 CH10 3/6/01 3:36 PM Page 238
<body>
<h1>Book-O-Rama - New Book Entry</h1>
<form action=”insert_book.php” method=”post”>
<table border=0>
<tr>
<td>ISBN</td>
<td><input type=text name=isbn maxlength=13 size=13><br></td>
</tr>
<tr>

<td>Author</td>
<td> <input type=text name=author maxlength=30 size=30><br></td>
</tr>
<tr>
<td>Title</td>
<td> <input type=text name=title maxlength=60 size=30><br></td>
</tr>
<tr>
<td>Price $</td>
<td><input type=text name=price maxlength=7 size=7><br></td>
</tr>
<tr>
<td colspan=2><input type=submit value=”Register”></td>
</tr>
</table>
</form>
</body>
</html>
The results of this form are passed along to insert_book.php, a script that takes the details, per-
forms some minor validations, and attempts to write the data into the database. The code for
this script is shown in Listing 10.4.
LISTING 10.4 insert_book.php—This Script Writes New Books into the Database
<html>
<head>
<title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?
if (!$isbn || !$author || !$title || !$price)

Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
239
LISTING 10.3 Continued
13 7842 CH10 3/6/01 3:36 PM Page 239
{
echo “You have not entered all the required details.<br>”
.”Please go back and try again.”;
exit;
}
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
@ $db = mysql_pconnect(“localhost”, “bookorama”, “bookorama”);
if (!$db)
{
echo “Error: Could not connect to database. Please try again later.”;
exit;
}
mysql_select_db(“books”);
$query = “insert into books values
(‘“.$isbn.”’, ‘“.$author.”’, ‘“.$title.”’, ‘“.$price.”’)”;
$result = mysql_query($query);
if ($result)

echo mysql_affected_rows().” book inserted into database.”;
?>
</body>
</html>
The results of successfully inserting a book are shown in Figure 10.4.
If you look at the code for
insert_book.php, you will see that much of it is similar to the
script we wrote to retrieve data from the database. We have checked that all the form fields
were filled in, and formatted them correctly for insertion into the database with
addslashes():
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
As the price is stored in the database as a float, we don’t want to put slashes into it. We can
achieve the same effect of filtering out any odd characters on this numerical field by calling
doubleval(), which we discussed in Chapter 1, “PHP Crash Course.” This will also take care
of any currency symbols that the user might have typed in the form.
Using MySQL
P
ART II
240
LISTING 10.4 Continued
13 7842 CH10 3/6/01 3:36 PM Page 240
FIGURE 10.4
The script completes successfully and reports that the book has been added to the database.
Again, we have connected to the database using mysql_pconnect(), and set up a query to send
to the database. In this case, the query is an SQL INSERT:
$query = “insert into books values
(‘“.$isbn.”’, ‘“.$author.”’, ‘“.$title.”’, ‘“.$price.”’)”;

$result = mysql_query($query);
This is executed on the database in the usual way by calling mysql_query().
One significant difference between using INSERT and SELECT is in the use of
mysql_affected_rows():
echo mysql_affected_rows().” book inserted into database.”;
In the previous script, we used mysql_num_rows() to determine how many rows were returned
by a SELECT. When you write queries that change the database such as INSERTs, DELETEs, and
UPDATEs, you should use mysql_affected_rows() instead.
This covers the basics of using MySQL databases from PHP. We’ll just briefly look at some of
the other useful functions that we haven’t talked about yet.
Other Useful PHP-MySQL Functions
There are some other useful PHP-MySQL functions, which we will discuss briefly.
Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
241
13 7842 CH10 3/6/01 3:36 PM Page 241
Freeing Up Resources
If you are having memory problems while a script is running, you might want to use
mysql_free_result(). This has the following prototype:
int mysql_free_result(int result);
You call it with a result identifier, like this:
mysql_free_result($result);
This has the effect of freeing up the memory used to store the result. Obviously you wouldn’t
call this until you have finished working with a resultset.
Creating and Deleting Databases

To create a new MySQL database from a PHP script, you can use mysql_create_db(), and to
drop one, you can use mysql_drop_db().
These functions have the following prototypes:
int mysql_create_db(string database, [int database_connection] );
int mysql_drop_db(string database, [int database_connection] );
Both these functions take a database name and an optional connection. If no connection is sup-
plied, the last open one will be used. They will attempt to create or drop the named database.
Both functions return true on success and false on failure.
Other PHP-Database Interfaces
PHP supports libraries for connecting to a large number of databases including Oracle,
Microsoft SQL Server, mSQL, and PostgreSQL.
In general, the principles of connecting to and querying any of these databases are much the
same. The individual function names vary, and different databases have slightly different func-
tionality, but if you can connect to MySQL, you should be able to easily adapt your knowledge
to any of the others.
If you want to use a database that doesn’t have a specific library available in PHP, you can use
the generic ODBC functions. ODBC stands for Open Database Connectivity and is a standard
for connections to databases. It has the most limited functionality of any of the function sets,
for fairly obvious reasons. If you have to be compatible with everything, you can’t exploit the
special features of anything.
In addition to the libraries that come with PHP, database abstraction classes such as Metabase
are available that allow you to use the same function names for each different type of database.
Using MySQL
P
ART II
242
13 7842 CH10 3/6/01 3:36 PM Page 242
Further Reading
For more information on connecting MySQL and PHP together, you can read the appropriate
sections of the PHP and MySQL manuals.

For more information on ODBC, visit
/>Metabase is available from
/>Next
In the next chapter, we will go into more detail about MySQL administration and discuss how
you can optimize your databases.
Accessing Your MySQL Database from the Web with PHP
C
HAPTER 10
10
ACCESSING
YOUR MYSQL
DATABASE
243
13 7842 CH10 3/6/01 3:36 PM Page 243
13 7842 CH10 3/6/01 3:36 PM Page 244

×