Advanced Database Interaction in PHP4
If you have been playing with PHP for a while, you have most likely noticed its excellent support for connecting to MySQL databases. Most of the PHP books on the market describe PHP database support only with MySQL. But PHP supports many more databases with almost the same support it provides for MySQL. As of version 4.1, PHP supports the following databases in one form or another.
Basically, PHP has enough built-in support for a majority of your database needs, especially since it contains support for the commercial heavyweights, such as Oracle, Sybase, Informix, and Microsoft.
Unfortunately, each supported database has different functions to do the same things. For example, to connect to a MySQL database you use the function mysql_connect, and to connect to a MS SQL server you use mssql_connect. The two functions are almost identical, but have different names.
This causes problems as far as code portability goes. Say, for example, you have a killer app that you want to create, but management insists that you use Microsoft's SQL server as the database back-end. However, you know that MySQL or PostgreSQL will do the job just as well, and they are "free" databases that run on the lovely Linux server you have hiding under your desk. Wouldn't it be nice if you could code it once, then run your application using any one of these databases with only the flip of a variable to tell PHP which database it is talking to?
The PHP team has eliminated some of the problems with multiple databases by creating a database abstraction layer called DBX. DBX allows you to use one function that can, for example, connect to different types of databases.
You could also create your own set of custom database "wrappers" to allow you to support multiple databases.
There is also a great database abstraction layer called PEAR::DB. PEAR is a set of libraries for PHP that is similar to the PERL CPAN library, although not as extensive at this time.
This chapter will show you a little bit of all three solutions. The bottom line is that your code will be more portable.
Database-Specific Functions in PHP
This section presents some basics in three of the more prominent databases that you can use with PHP. This book assumes that you have some experience with databases and PHP (notably MySQL). This information is included as a brief overview and to point out some of the differences between the functions across different databases. The databases are:
MySQL
PostgreSQL
MS SQL (Microsoft)
Chances are good that you will have at least one of these databases available to you (very good since MySQL and PostgreSQL are available for free download).
There are four basic concepts in PHP for dealing with databases:
Connecting to the database server.
Selecting the proper database.
Querying the database to insert, read, or delete data.
Obtaining the results of your queries to present to the user.
Let's go over these four concepts with the PHP functions used for each database.
Connecting to the Database Server
Before you can do anything in a database-backed application, you need to connect to the database server that contains the actual database that you need to access. For the three databases discussed earlier, this translates into three functions:
mysql_connect— to connect to a MySQL Server
mssql_connect— to connect to a MS SQL Server
pg_connect— to connect to a PostgreSQL Server
mysql_connect() and mssql() connect work identically:
mysql_connect(SERVER, USER, PASSWORD);
and
mssql_connect(SERVER, USER, PASSWORD);
In each function, the arguments that need to be defined are:
SERVER— The host name or IP address of the host on which the database server is running, for example, "mycompany.com" or "192.168.0.1".
USER— The login of the user who has access to the database server, for example, "Joe".
PASSWORD— The password of the user.
The connect function for PostgreSQL is much different. pg_connect takes as its argument a single string:
pg_connect(STRING);
The STRING must contain all of the pertinent information required by your server. The most complete string you could use is:
pg_connect("host=localhost port=5432 dbname=test
user=username password=password");
It doesn't hurt to use all of the information above, but if the host was localhost, the port was the default port of 5432, and you had no password associated with the user, then you could get by with:
pg_connect("dbname=test user=username");
Consult your PostgreSQL documentation for your specific implementation. The examples in this chapter assume that you are running your PostgreSQL server on the default port of 5432, so the port is not included in the pg_connect examples.
Selecting the Proper Database
Once you have successfully connected to the database server, you then need to select the database on which you are going to perform your queries.
In the case of PostgreSQL, you have already selected the database in your pg_connect() function, so there is no function to select the database.
However, when using MS SQL or MySQL, you still need to select the database using the respective function:
mysql_select_db(STRING)
or
mssql_select_db(STRING)
In each case, STRING refers to the name of the database to which you are connecting.
Querying the Database to Insert, Read, or Delete Data
Once you've connected to the database server and selected the database, the next logical thing is to do something with the data in the form of a query. Most databases accept any standard SQL command in a query, as well as their own database-specific commands.
The three databases used in the examples all use the same syntax:
mysql_query(STRING);
mssql_query(STRING);
pg_query(STRING);
where STRING is an SQL statement, such as "SELECT name FROM phonebook WHERE name = 'Sarah'."
Obtaining the Results of Your Queries to Present to the User
Once you have made your query, you need to get the result and show it to the user or perform some other processing on it. One of the simplest ways to accomplish this is using the fetch_array functions included in most PHP supported databases.
mysql_fetch_array(RESULT);
mssql_fetch_array(RESULT);
pg_fetch_array(RESULT);
The data from the DBX—PHP Support for Multiple Databases
For applications that don't require complex database-specific queries, you can use PHP's built-in DBX functions.
Before you can use the DBX functions, you must enable support at compile time if you are using Linux or enable the DBX module if you are using Windows.
Enabling DBX in Linux
If you compiled PHP using Apache's APXS functionality (compile --with-apxs=/path/to/apache/bin/apxs), then adding functionality to the PHP module is a breeze.
Before recompiling PHP, I first suggest that you delete the config.cache file and clean up files left over from the previous compile. This can be done like this:
cd /path/to/php/source
rm config.cache
make clean
After you issue the make clean command, you will notice quite a few files being deleted. Don't worry about it. The make program is just cleaning up files it won't need when you recompile. If you don't run the make clean command, then you may start running into some problems. If you have been compiling PHP with no problems and suddenly it won't compile right, even though you haven't changed anything, it's a good bet that the make clean command will solve your problem.
Once you've cleaned up the mess from the previous compile, you can get started with the new compile.
To compile PHP with DBX support enabled, issue the following command from a shell prompt (replacing paths specific to your install as necessary):
./compile --with-apxs=/usr/local/apache/bin/apxs \
--enable-dbx \
You should also enable support for any database that you wish to use as well—for example:
--with-mssql
After the configure runs, issue the command:
make
Assuming no errors occur, you can then issue the command:
make install
The final command copies the libphp4.so library file to /path/to/apache/libexec/.
Restart Apache to load the new library:
/path/to/apache/bin/apachectl restart
You can verify that DBX has been correctly installed by using the phpinfo() function and verifying that DBX is listed under the configuration section.
Enabling DBX in Windows
Enabling DBX support for Windows is very easy, since the DLL file for DBX has been precompiled and included in the basic PHP windows installation. Open your php.ini file in a text editor and search for the line that says:
extension_dir = ./
This line should point to the place where your PHP extensions reside. If you copied the extensions to the same directory as the php.ini file, then you do not need to modify the line. If you did not move the PHP extensions to the same directory as the php.ini file, then you need to edit the line to point to the correct directory, for example:
extension_dir = C:\Apache\php\extensions
Next, find the section in the php.ini file that says:
;Windows Extensions
This line will be followed by many lines of windows .dll extensions for php. To enable DBX support, uncomment (delete the semicolon at the beginning of the line) the line that contains the DBX library DLL:
extension=php_dbx.dll
After you have uncommented the line, save the file and restart the Apache Web server.
You can verify that DBX has been correctly installed by using the phpinfo() function and verifying that DBX is listed under the configuration section.
DBX Functions
The DBX functions are a single set of functions that allows you to access multiple supported databases without having to write your own wrapper functions.
As of version 4.1, PHP DBX supports the following databases:
mysql
odbc
pgsql
mssql
fbsql
The following functions are available in DBX:
dbx_close(CONNECTION)
The dbx_close() function takes one argument, CONNECTION. CONNECTION is the link identifier created when you call the dbx_connect() function.
dbx_connect(MODULE, HOST, DATABASE, USER, PASSWORD, PERSISTENT)
The dbx_connect() function is used to establish a connection to the database server, as well as specify which database is to be used. dbx_connect returns an object that contains the handle of the connection as well as the name of the database to which it is connected. See the example for details. The dbx_connect function accepts six arguments:
MODULE— The database module that you want to use for this connection. The module is essentially the database type to which you are trying to connect. Values may be:
DBX_MYSQL— For MySQL databases.
DBX_ODBC— For any database which supports an ODBC connection.
DBX_PGSQL— For PostgreSQL databases.
DBX_MSSQL— For MS SQL databases.
DBX_FBSQL— For Frontbase database.
HOST— The host name or IP address of the database server.
DATABASE— The name of the database on the database server.
USER— The username.
PASSWORD— The password for the user.
PERSISTENT— Whether or not to make this a persistent connection. If you wish to make the connection persistent, then put DBX_PERSISTENT here. Otherwise, this argument is not required.
Example:
[View full width]
$module = DBX_MYSQL; //note the absence of quotes!
$dbconn = dbx_connect($module, "192.168.0.5", "php", "mysqluser", "password") or DIE (
"Unable To Connect");
//$dbconn->database = "php"
//$dbconn->handle is a resource identifer
dbx_error(CONNECTION)
The dbx_error function returns the error from the latest function call to the module. The argument CONNECTION is the link identifier defined when you called dbx_connect().
Example:
$result = dbx_query($dbconn, "select something from non_existing_table");
if ($result == 0) {echo dbx_error($dbconn); }
//responds: Table 'php.non_existing_table' doesn't exist
dbx_query(CONNECTION, SQL STATEMENT, FLAGS)
The dbx_query function lets you send SQL queries to the database. It returns an object if the query does not fail and the query returns one or more rows. A query that returns zero rows does not return an object. Instead it returns 1, for the query was successful, but there was no data returned, such as when you select * from a table that has no data. The arguments are:
CONNECTION— The link identifier created when you call the dbx_connect() function.
SQL STATEMENT— A standard SQL statement.
FLAGS— You can specify how much information is returned by the query by specifying one or more of the following flags. By default, all flags are turned on. When specifying the flags, you must use a | symbol to separate them—for example "DBX_RESULT_INDEX | DBX_RESULT_INFO". The flags are:
DBX_RESULT_INDEX— Always returned. All results in the result array are indexed by a number, i.e., $result[0], $result[1], etc.
DBX_RESULT_INFO— Returns information about the columns returned, such as field name and field type.
DBX_RESULT_ASSOC— Sets the keys of the returned array to the column names.
The object returned by dbx_query contains the following properties:
handle— The same handle that is available from $dbconn->handle. Accessed as $result->handle.
cols— The number of columns in the result set. Accessed by $result->col.
rows— The number of rows in the result set. Accessed by $result->rows.
info— Returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flag's parameter. Provides a two-dimensional array containing the name of the column and its type. Accessed by $result['info'][$x] and $result['name'][$x], where $x is the index of the particular row.
data— Contains the actual data from result. Accessed by $result->data[$x]['field name'] where $x is the index of the particular row.
Example:
$result = dbx_query($dbconn, "select something from
some_table", DBX_RESULT_INFO);
dbx_sort(RESULT, SORT FUNCTION)
The dbx_sort function allows you to sort the results of a query using your own custom sort function. However, it is more efficient to use the "ORDER BY" clause in your SQL statement. The arguments the dbx_sort accepts are:
RESULT— The result of a previous dbx_query statement.
SORT FUNCTION— Your custom sort function.
Example:
function my_sort {
//your custom sort definition
}
dbx_sort($result, "my_sort");
//$result is now sorted according to my_sort()
dbx_compare(ROW1, ROW2, COLUMN KEY, FLAGS)
The dbx_compare function allows you to compare two result sets, ROW1 and ROW2. If ROW1 = ROW2, then dbx_compare returns 0. If ROW1 > ROW2, then dbx_compare returns 1. If ROW1 < ROW2, then dbx_compare returns –1. The arguments that dbx_compare accepts are:
ROW1— A result from a dbx_query function call.
ROW2— A result from a dbx_query function call.
COLUMN KEY— The name of the column on which the comparison should be made.
FLAGS— You can specify several flags to compare the rows in ascending or descending order, and what type of comparison should be made. Separate the order of any type by a pipe.
DBX_CMP_ASC— (default) Compare in ascending order.
DBX_CMP_DESC— Compare in descending order.
DBX_CMP_NATIVE— (default) Compare the items "as is."
DBX_CMP_TEXT— Compare the items as strings.
DBX_CMP_NUMBER— Compare the items as numbers.
Example:
$comp = dbx_compare ($r1, $r2, "income");
//$comp = 0 if $r1 = $r2
//$comp = 1 if $r1 > $r2
//$comp = -1 if $r < $r2
Using DBX
Now that you have some idea of how the DBX functions work, let's create a small URL database to keep track of some of your favorite links. Since you are using DBX, you can use this application with any database that is supported by DBX. Figure 3-1 shows dbx_urls.php in action.
Script 3–1 dbx_urls.php
[View full width]
1. <html>
2. <head>
3. <title>A PHP-DBX URL Organizer</title>
4. <style type=text/css>
5. p, ul, td, h1, h2, h3 {font-family: verdana, helvetica, sans-serif;}
6. </style>
7. </head>
8. <body>
9. <?
10. /*****
11. * TABLE DEFINITION FOR THIS EXAMPLE:
12. * create table URLS (
13. * url VARCHAR(128) not null,
14. * description TEXT,
15. * primary key (url));
16. *****/
17. //define $MODULE as DBX_MYSQL, DBX_MSSQL, DBX_PGSQL, or your supported database
18. $MODULE = DBX_PGSQL;
19. $server = "192.168.0.5";
20. $user = "psqluser";
21. $password = "password";
22. $database = "php";
23. /* FUNCTIONS */
24. function get_urls($dbconn, $sql) {
25. $result = @dbx_query($dbconn, $sql);
26. if ( $result == 0 ) {
27. echo dbx_error($dbconn);
28. } else {
29. return $result;
30. }
31. }
32. function url($action, $dbconn, $url, $description) {
33. if($action == "add") {
34. $sql = "insert into URLS values('$url', '$description')";
35. }elseif($action == "delete") {
36. $url = urldecode($url);
37. $sql = "delete from URLS where URL = '$url'";
38. }
39. $result = @dbx_query($dbconn, $sql);
40. if ( $result == 0 ) {
41. echo "<P>ERROR ADDING URL: " . dbx_error($dbconn);
42. } else {
43. print("<p>$action : $url succeeded!<p>");
44. }
45. }
46. /*** MAIN ***/
47. $dbconn = dbx_connect($MODULE, $server, $database, $user, $password) or die("CANNOT CON
NECT TO DATABASE");
48. ?>
49. <h1>PHP DBX URL Organizer</h1>
50. <form action=dbx_urls.php method=post>
51. <p><b>Add a URL:</b>
52. <br>URL: <input type="text" name="url" maxlength="128" value="http://"> Description:
<input type="text" name="description"> <input type="submit" name="addurl" value="Add
URL!">
53. </form>
54. <?
55. if(isset($addurl)) {
56. url("add", $dbconn, $url, $description);
57. }
58. if(isset($delete)) {
59. url("delete", $dbconn, $delete, "");
60. }
61. $sql = "select * from URLS";
62. $result = get_urls($dbconn, $sql);
63. if(sizeof($result->data) == 0) {
64. ?>
65. <h3>Sorry, there are no URLs in the database. You should add some.
66. <?
67. } else {
68. ?>
69. <p>
70. <table border=1 cellpadding=5 cellspacing=0 width=600>
71. <tr><td><b>URL</b></td><td><b>Description</b></td><td> </td></tr>
72. <?
73. for($i = 0; $i < sizeof($result->data); $i++) {
74. ?>
75. <tr><td><a href=<?=$result->data[$i]['url']?>><?=$result->data[$i]['url']?></a></td>
76. <td><?=$result->data[$i]['description']?></td>
77. <td width=1><a href=dbx_urls.php?delete=<?=urlencode(
$result->data[$i]['url'])?>>delete</a></tr>
78. <?
79. }
80. ?></table><?
81. }
82. ?>
83. </body>
84. </html>
Figure 3-1. dbx_urls.php
Script 3-1. dbx_urls.php Line-by-Line Explanation LINE
DESCRIPTION
1–8
Print out normal HTML to start the page.
10–16
The SQL statement required to create the table for this example.
18
The $MODULE definition for the type of database the script will access. Valid choices are defined in line 17.
19
Define the database server host name or IP.
20
Define the database user's username.
21
Define the database user's password.
22
Define the database name on the database server.
24
Define a function to query the database and return the URLs in the database.
25
Issue the query. Note the "@" sign before the call to the dbx_query() function. The "@" sign suppresses any warning that may be issued if something goes awry with the function—for example, if the database is down. More information on handling these errors is available in Chapter 8.
26
If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object.
27
Print out the error if line 26 is true.
28–30
If there was no error, then return the result object.
30
End the function declaration.
32
Define a function to add or remove URLs from the database called url(). The function takes the following arguments:
$action— either "add" or "delete"
$dbconn— the connection link to the database
$url— the URL to be added or removed
$description— the description of the URL
33
If the $action argument is "add", then we are adding a URL.
34
Generate the SQL to add the URL.
35
If $action is not "add", then check to see if it is "delete".
36
Decode the encoded URL.
37
Generate the SQL to delete the URL.
38
End the if/else statement started on line 33.
39
Query the database with the generated SQL.
40
If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object.
41
Display an error to the user including the specific DBX error message.
42–44
If there wasn't an error querying the database, then display a success message to the user.
45
End the function.
46
Start the man program.
47
Generate the database connection string with the variables defined at the beginning of the script.
49–53
Print out the HTML for the page that displays the heading, as well as the form to add URLs.
55–57
If the "Add URL!" button has been pushed, then run the url() function.
58–60
If a "Delete" link has been clicked next to any of the URLs, then run the url() function.
61
Generate an SQL statement to retrieve the URLs.
62
Run the get_url() function using the SQL generated above to retrieve the URLs from the database.
63
Check to make sure there was data in the result set that was returned from the get_urls() function. If there was no data, then the database is empty.
65
Display a message to the user that the database was empty.
67
If the database was not empty, then execute the rest of the script.
70–71
Create a table to display the URLs.
73
Start a for loop to loop through the data returned from the get_url() function.
75
Print out the URL to the table and include a hyperlink to the URL.
76
Print out the description of the URL to the table.
77
Print a delete link for the URL.
79
End the for loop.
81
End the if/else statement started on line 63.
83–84
Close out the HTML for the page.
Creating Your Own Support for Multiple Databases
If you have a simple application that doesn't require complex database interaction, but you still want it to work with multiple databases, then you can create your own set of database wrapper functions.
You have to take into account the different database-specific limitations that may arise and code to the lowest common denominator. That is, you can't use the useful "AUTO_INCREMENT" column feature that is supported in MySQL if you also want to support MS SQL or PostgreSQL databases, since they do not implement that feature. Similarly, MySQL doesn't support secondary keys, so you cannot use that convention.
This next example provides a sample database wrapper that supports MySQL, MS SQL, and PostgreSQL databases. It is called DBlib and contains the following functions listed in Table 3-1:
Table 3-1. DBlib.php Functions FUNCTION
DESCRIPTION
connectDB(DB_ID)
Connects to the database server and returns a DB_CONNECTION.
selectDB(DB_ID)
Selects which database should be used on the server.
queryDB(DB_ID, QUERY)
Sends an SQL query to the database. Returns a RESULT set.
returnDBarray(DB_ID, RESULT)
Returns an array of a row in the RESULT set.
numrowsDB(DB_ID, RESULT)
Returns the number of affected rows from the last query.
closeDB(DB_ID, DB_CONNECTION)
Closes the connection to the database.
The first part of the example is the DBlib.php file, which you include in your own application.
Script 3–2 DBlib.php
[View full width]
1. <?
2. function connectDB($db) {
3. global $host, $database, $username, $password;
4. switch($db) {
5. case ("psql"):
6. $conn_string = "host=" . $host . " dbname=" . $database . " user=" . $username . "
password=" . $password;
7. $dbconn = pg_connect($conn_string) or die ("Error Connecting to PostgreSQL DB");
8. return $dbconn;
9. break;
10. case ("mysql"):
11. $dbconn = mysql_connect($host, $username, $password) or die ("Error Connecting to
MySQL DB");
12. return $dbconn;
13. break;
14. case("mssql"):
15. $dbconn = mssql_connect($host, $username, $password) or die ("Error Connecting to
MS SQL DB");
16. return $dbconn;
17. break;
18. default;
19. echo "<P>Invalid Database: $db";
20. return 0;
21. }
22. }
23.
24. function selectDB($db) {
25. global $database;
26. switch($db) {
27. case ("psql"):
28. return 1;
29. break;
30. case ("mysql"):
31. mysql_select_db($database) or die ("Error Connecting to MySQL DB");
32. return 1;
33. break;
34. case("mssql"):
35. mssql_select_db($database) or die ("Error Connecting to MS SQL DB");
36. return 1;
37. break;
38. default;
39. echo "<P>Invalid Database: $db";
40. return 0;
41. }
42. }
43.
44. function queryDB($db, $query) {
45. switch($db) {
46. case ("psql"):
47. if(!$result = @pg_exec($query)){
48. $result = 0;
49. }
50. break;
51. case ("mysql"):
52. if(!$result = @mysql_query($query)){
53. $result = 0;
54. }
55. break;
56. case("mssql"):
57. if(!$result = @mssql_query($query)){
58. $result = 0;
59. }
60. break;
61. default;
62. echo "<P>Invalid Database: $db";
63. $result = 0;
64. }
65. return $result;
66. }
67.
68. function returnDBarray($db, $result) {
69. if($result != "error") {
70. switch($db) {
71. case ("psql"):
72. if(!$array = @pg_fetch_array($result)){
73. $array = 0;
74. }
75. break;
76. case ("mysql"):
77. if(!$array = @mysql_fetch_array($result)){
78. $array = 0;
79. }
80. break;
81. case("mssql"):
82. if(!$array = @mssql_fetch_array($result)){
83. $array = 0;
84. }
85. break;
86. default;
87. echo "<P>Invalid Database: $db";
88. $array = 0;
89. }
90. return $array;
91. }
92. }
93.
94. function closeDB($db,$dbconn) {
95. switch($db) {
96. case ("psql"):
97. if(!@pg_close($dbconn)){
98. return 0;
99. } else {
100. return 1;
101. }
102. break;
103. case ("mysql"):
104. if(!@mysql_close($dbconn)){
105. return 0;
106. } else {
107. return 1;
108. }
109. break;
110. case("mssql"):
111. if(!@mssql_close($dbconn)){
112. return 0;
113. } else {
114. return 1;
115. }
116. break;
117. default;
118. echo "<P>Invalid Database: $db";
119. return 0;
120. }
121. }
122.
123. function numrowsDB($db, $result) {
124. switch($db) {
125. case ("psql"):
126. if(!$rows = @pg_numrows($result)){
127. return 0;
128. } else {
129. return $rows;
130. }
131. break;
132. case ("mysql"):
133. if(!$rows = @mysql_numrows($result)){
134. return 0;
135. } else {
136. return $rows;
137. }
138. break;
139. case("mssql"):
140. if(!$rows = @mssql_num_rows($result)){
141. return 0;
142. } else {
143. return $rows;
144. }
145. break;
146. default;
147. echo "<P>Invalid Database: $db";
148. return 0;
149. }
150. }
151.
152. ?>
Script 3-2. DBlib.php Line-by-Line Explanation LINE
DESCRIPTION
2
Declare the connectDB function. The function requires the type of database ($db) as an argument.
3
Declare global variables that can be accessed by this function. The variables are required to connect to the database.
4
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
5
If $db = "psql", then the user wants to use a PostgreSQL database.
6
Generate a connection string for a PostgreSQL database.
7
Execute the pg_connect() function to connect to the PostgreSQL server. If there is an error, then kill the script and provide an error message.
8
If there is not an error, then return the $dbconn variable, which is the database connection handler and is required for many of the other functions.
9
Break out of the switch statement, since the case has been satisfied.
10
If $db = "mysql", then the user wants to use a MySQL database.
11
Execute the mysql_connect() function to connect to the MySQL server. If there is an error, then kill the script and provide an error message.
12
If there is not an error, then return the $dbconn variable, which is the database connection handler and is required for many of the other functions.
13
Break out of the switch statement, since the case has been satisfied.
14
If $db = "mssql", then the user wants to use a MS SQL database.
15
Execute the mssql_connect() function to connect to the MS SQL server. If there is an error, then kill the script and provide an error message.
16
If there is not an error, then return the $dbconn variable, which is the database connection handler and is required for many of the other functions.
17
Break out of the switch statement, since the case has been satisfied.
18–19
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
20
Return 0 (false), so that any functions using this function know that the function failed.
21
End the switch statement.
22
End the function declaration.
24
Declare the selectDB function. The function requires the type of database ($db) as an argument.
25
Declare a global variable that can be accessed by this function. The variable is required to select the database.
26
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
27
If $db = "psql", then the user wants to use a PostgreSQL database.
28
Return 1 (true), so that the function accessing this function knows that the call to the SelectDB function was successful. PostgreSQL syntax specifies which database to use during pg_connect(), which should have been run before this function.
29
Break out of the switch statement, since the case has been satisfied.
30
If $db = "mysql", then the user wants to use a MySQL database.
31
Execute the mysql_select_db() function to select the proper database on the MySQL server. If there is an error, then kill the script and provide an error message.
32
If there is not an error, then return 1 (true), so that the function accessing this function knows that the call to the SelectDB function was successful.
33
Break out of the switch statement, since the case has been satisfied.
34
If $db = "mssql", then the user wants to use a MS SQL database.
35
Execute the mssql_select_db() function to select the proper database on the MS SQL server. If there is an error, then kill the script and provide an error message.
36
If there is not an error, then return 1 (true), so that the function accessing this function knows that the call to the SelectDB function was successful.
37
Break out of the switch statement, since the case has been satisfied.
38–39
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
40
Return 0 (false), so that any functions using this function know that the function failed.
41
End the switch statement.
42
End the function declaration.
44
Declare the queryDB function. The function requires the type of database ($db) and the SQL query ($query) as arguments.
45
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
46
If $db = "psql", then the user wants to use a PostgreSQL database.
47
Run the query using pg_exec() and check if there is an error.
48
If there was an error, then set $result to 0.
49
End the if statement.
50
Break out of the switch statement, since the case has been satisfied.
51
If $db = "mysql", then the user wants to use a MySQL database.
52
Run the query using mysql_query() and check if there is an error.
53
If there was an error, then set $result to 0.
54
End the if statement.
55
Break out of the switch statement, since the case has been satisfied.
56
If $db = "mssql", then the user wants to use a MS SQL database.
57
Run the query using mssql_query() and check if there is an error.
58
If there was an error, then set $result to 0.
59
End the if statement.
60
Break out of the switch statement, since the case has been satisfied.
61–62
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
63
Return 0 (false), so that any functions using this function know that the function failed.
64
End the switch statement.
65
Return the value of $result to the function calling this function. If the $result = 0, then the calling function knows an error has occurred.
66
End the function declaration.
68
Declare the returnDBarray function. The function requires the type of database ($db) and the result set from the previous query ($result) as arguments.
69
Verify that the result does not equal 0. If it does, then there was an error with the previous query. If there was no error, then continue.
70
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
71
If $db = "psql", then the user wants to use a PostgreSQL database.
72
Fetch the array using pg_fetch_array() and check if there is an error.
73
If there was an error, then set $array to 0.
74
End the if statement.
75
Break out of the switch statement, since the case has been satisfied.
76
If $db = "mysql", then the user wants to use a MySQL database.
77
Fetch the array using mysql_fetch_array() and check if there is an error.
78
If there was an error, then set $array to 0.
79
End the if statement.
80
Break out of the switch statement, since the case has been satisfied.
81
If $db = "mssql", then the user wants to use a MS SQL database.
82
Fetch the array using mssql_fetch_array() and check if there is an error.
83
If there was an error, then set $array to 0.
84
End the if statement.
85
Break out of the switch statement, since the case has been satisfied.
86–87
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
88
Set $array to 0 (false), so that any functions using this function know that the function failed.
89
End the switch statement.
90
Return the value of $result to the function calling this function. If the $result = 0, then the calling function knows an error has occurred.
91
End the if statement that checked to make sure that $result did not equal 0.
92
End the function declaration.
94
Declare the closeDB function. The function requires the type of database ($db) and the database connection ($dbconn) as arguments.
95
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
96
If $db = "psql", then the user wants to use a PostgreSQL database.
97
Run pg_close() and check if there is an error.
98
If there was an error, then return 0, notifying the calling function that the close failed.
99–100
If there was not an error, then notify the calling function that the close succeeded.
101
End the if statement.
102
Break out of the switch statement, since the case has been satisfied.
103
If $db = "mysql", then the user wants to use a MySQL database.
104
Run mysql_close() and check if there is an error.
105
If there was an error, then return 0, notifying the calling function that the close failed.
106–107
If there was not an error, then notify the calling function that the close succeeded.
108
End the if statement.
109
Break out of the switch statement, since the case has been satisfied.
110
If $db = "mssql", then the user wants to use a MS SQL database.
111
Run mssql_close() and check if there is an error.
112
If there was an error, then return 0, notifying the calling function that the close failed.
113–114
If there was not an error, then notify the calling function that the close succeeded.
115
End the if statement.
116
Break out of the switch statement, since the case has been satisfied.
117–118
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
119
Return 0 to notify the calling function that the function failed.
120
End the switch statement.
121
End the function declaration.
123
Declare the numrowsDB function. The function requires the type of database ($db) and the result set from the previous query ($result) as arguments.
124
Start a switch statement that checks to see which of the cases should be run, depending on the value of $db.
125
If $db = "psql", then the user wants to use a PostgreSQL database.
126
Run pg_numrows() and check if there is an error.
127
If there was an error, then return 0, notifying the calling function that the close failed.
128–129
If there was not an error, then notify the calling function that the close succeeded.
130
End the if statement.
131
Break out of the switch statement, since the case has been satisfied.
132
If $db = "mysql", then the user wants to use a MySQL database.
133
Run mysql_num_rows() and check if there is an error.
134
If there was an error, then return 0, notifying the calling function that the close failed.
135–136
If there was not an error, then notify the calling function that the close succeeded.
137
End the if statement.
138
Break out of the switch statement, since the case has been satisfied.
139
If $db = "mssql", then the user wants to use a MS SQL database.
140
Run mssql_num_rows() and check if there is an error.
141
If there was an error, then return 0, notifying the calling function that the close failed.
142–143
If there was not an error, then notify the calling function that the close succeeded.
144
End the if statement.
145
Break out of the switch statement, since the case has been satisfied.
146–147
If none of the cases have been satisfied, then display a message that the $db value sent to the function was not valid.
148
Return 0 to notify the calling function that the function failed.
149
End the switch statement.
150
End the function declaration.
The next part of the example is the SQL required to create the table for the sample application:
Script 3–3 addressbook.sql
1. CREATE TABLE addressbook (
2. first VARCHAR(32),
3. last VARCHAR(32),
4. home VARCHAR(16),
5. cell VARCHAR(16),
6. work VARCHAR(16));
The final bit is the example application, which uses the DBlib.php file as its database wrapper, allowing the application to be used with three different database back-ends without having to change any of the code. See Figure 3-2 for the output produced by this script:
Script 3–4 customDB.php
1. <?
2. $page = "customDB.php";
3.
4. require_once("DBlib.php");
5. /* REQUIRED FOR DBlib.php */
6. //$db = "psql"; //PostgreSQL Database
7. //$db = "mysql"; //MySQL Database
8. $db = "mssql"; // MS SQL Database
9. $host = "192.168.0.1";
10. $database = "php";
11. $username = "mssqluser";
12. $password = "password";
13. /**************************/
14.
15. function display_addresses ($db) {
16. global $dbconn;
17. selectDB($db, $dbconn);
18. $sql = "select * from addressbook";
19. if(!$result = queryDB($db, $sql)) {
20. echo "<P>Error with query!";
21. }
22. $rows = numrowsDB($db, $result);
23. if($rows == 0) {
24. echo "There are entries in your addressbook.";
25. } else {
26. ?><table border=1><?
27. while($row = returnDBarray($db, $result)) {
28. ?>
29. <tr><td colspan=2><b><?=$row['first'];?> <?=$row['last'];?></b></td></tr>
30. <tr><td>Home: </td><td><?=$row['home'];?></td></tr>
31. <tr><td>Cell: </td><td><?=$row['cell'];?></td></tr>
32. <tr><td>Work: </td><td><?=$row['work'];?></td></tr>
33. <?
34. }
35. ?></table><?
36. }
37. }
38.
39. function add_address($db, $HTTP_POST_VARS) {
40. global $dbconn;
41. selectDB($db, $dbconn);
42. $query = "insert into addressbook values ('" .
43. $HTTP_POST_VARS['first'] . "','" .
44. $HTTP_POST_VARS['last'] . "','" .
45. $HTTP_POST_VARS['home'] . "','" .
46. $HTTP_POST_VARS['cell'] . "','" .
47. $HTTP_POST_VARS['work'] . "')";
48. if(!queryDB($db, $query)) {
49. echo $query;
50. return 0;
51. } else {
52. return 1;
53. }
54. }
55.
56. function add_address_form(){
57. global $page;
58. ?>
59. <h3>Add An Address:</h3>
60. <form action=<?=$page?> method=post>
61. <p>First Name: <input type="text" name="first">
62. <br>Last Name: <input type="text" name="last">
63. <br>Home: <input type="text" name="home">
64. <br>Cell: <input type="text" name="cell">
65. <br>Work: <input type="text" name="work">
66. <p><input type="submit" name="add_address" value="Add Entry!">
67. </form>
68. <?
69. }
70. /***** MAIN *****/
71. ?>
72. <h3>Address Book</h3>
73. <p><a href=<?=$page?>?action=add>Add An Entry</a>
74. <p>
75. <?
76. $dbconn = connectDB($db);
77. if(isset($add_address)) {
78. if(!add_address($db, $HTTP_POST_VARS)) {
79. echo "<h3>ERROR ADDING ENTRY!</h3>";
80. } else {
81. echo "<h3>ENTRY ADDED!</h3>";
82. }
83. } elseif(isset($action) && $action == "add") {
84. add_address_form();
85. }
86. ?>
87. <h4>Current Addresses:</h4>
88. <?
89. display_addresses ($db);
90. if(!closeDB($db, $dbconn)) {
91. echo "<p>ERROR CLOSING DB CONNECTION";
92. }
93. ?>
Figure 3-2. customDB.php
Script 3-4. customDB.php Line-by-Line Explanation LINE
DESCRIPTION
2
Declare the name of the page so that it can be used in a function that prints out a form action. This is useful when testing the script if you want to quickly give it a new name.
4
Require the DBlib.php file so that this script has access to the database wrapper.
6–8
The different databases that this script can access. Uncomment only one.
9–12
Database connection information required to connect to the database server and access the specific database.
15
Declare the display_addresses function. This function takes one argument, $db, which is defined above.
16
Make the $dbconn variable, the connection handler to the database, available to this function.
17
Run the selectDB function from DBlib.php.
18
Generate an SQL statement to select all of the entries in the address book table.
19
Query the database using the queryDB function from DBlib.php. If there is not an error, then $result should contain a valid database query result.
20
If there was an error, display an error message to the screen.
22
Execute the numrowsDB function from DBlb.php.
23–24
If there are no rows in the result set, then the database is empty. Notify the user that there are no entries in the address book.
25
If there are rows in the result set, then continue executing the function.
26
Create a table to display the results.
27
Loop through each row in the result set using the returnDBarray function from DBlib.php.
29–34
Display the data in the current row.
35
Close the table.
36
End the if statement started on line 23.
37
End the function declaration.
39
Declare the add_address function. It takes as arguments the database type ($db) and the variables sent from the add_address_form, which is defined later in the script.
40
Make the $dbconn variable accessible to this function.
41
Select the database using the selectDB function from DBlib.php.
42–47
Generate an SQL statement that inserts the data from the form into the database.
48–49
If the query fails, then echo the query to help debug.
50
Return 0, since the query failed.
51–53
If the query didn't fail, then return 1.
56–69
Declare a function that prints a standard form to the browser that allows the user to enter a new address book entry.
70
Start the main part of the script.
72
Print a heading for the page.
73
Create a link that, when clicked, displays the form so the user can add another entry.
76
Create a connection to the database using the connectDB function from DBlib.php.
77
If the $add_address variable is set, then run the add_address() function to add a new entry to the address book.
78–79
If the query fails, then print an error message.
80–82
If the query is successful, then print a message telling the user.
87
Print a heading for the current addresses in the database.
89
Run the display_addresses function to print out.
90
Close the database connection using the closeDB function fromDBlib.php.
91
If there is an error closing the database connection, then notify the user.
92
End the if statement that began on line 77.
42
Query the database.
43
Set the fetch mode.
44–47
Display the results using DB_FETCHMODE_ASSOC. Note how the results are displayed on line 46.
48
Query the database.
49
Set the fetch mode.
50–52
Display the results using DB_FETCHMODE_OBJECT. Note how the results are displayed on line 52.
54
End the if statement started on line 28.
55
Free the result.
56
Close the database connection.
Tuesday, July 14, 2009
Advanced PHP for Web Professionals By Christopher Cosentino Chapter 3
Posted by Mr Procces at 7:15 AM
Labels: PHP, Web Applications, Web Development, Web Programming
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment