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

PHP and MySQL Web Development - P53 pdf

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 (108.02 KB, 5 trang )

232
Chapter 10 Accessing Your MySQL Database from the Web with PHP
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 number of rows[ms]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.
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.
The HTML for this page is shown in Listing 10.3.
Listing 10.3 newbook.html—HTML for the Book Entry Page
<html>
<head>
<title>Book-O-Rama - New Book Entry</title>
</head>
<body>


<h1>Book-O-Rama - New Book Entry</h1>
<form action="insert_book.php" method="post">
<table border="0">
<tr>
<td>ISBN</td>
13 525x ch10 1/24/03 3:37 PM Page 232
233
Putting New Information in the Database
<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>
Listing 10.3 Continued

Figure 10.3 This interface for putting new books into the
database could be used by Book-O-Rama’s staff.
The results of this form are passed along to insert_book.php,a script that takes the
details, performs some minor validations, and attempts to write the data into the data-
base.The code for this script is shown in Listing 10.4.
13 525x ch10 1/24/03 3:37 PM Page 233
234
Chapter 10 Accessing Your MySQL Database from the Web with PHP
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>
<?php
// create short variable names
$isbn=$HTTP_POST_VARS['isbn'];
$author=$HTTP_POST_VARS['author'];
$title=$HTTP_POST_VARS['title'];
$price=$HTTP_POST_VARS['price'];
if (!$isbn || !$author || !$title || !$price)
{
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', 'bookorama123');
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>
13 525x ch10 1/24/03 3:37 PM Page 234
235
Putting New Information in the Database
The results of successfully inserting a book are shown in Figure 10.4.
Figure 10.4 The script completes successfully and reports
that the book has been added to the database.
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 we 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.
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.";
13 525x ch10 1/24/03 3:37 PM Page 235
236
Chapter 10 Accessing Your MySQL Database from the Web with PHP
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.
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:
bool mysql_free_result(resource 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:
bool mysql_create_db(string database, [resource database_connection] );
bool mysql_drop_db(string database, [resource database_connection] );
Both these functions take a database name and an optional connection. If no connection
is supplied, 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 functionality, 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
13 525x ch10 1/24/03 3:37 PM Page 236

×