For all projects dealing with PHP and database access I make use of the data abstraction class from the PHPLIB library. PHP does not include a set of generic database functions. Each type of database has it's own uniquely named set of functions. Using the PHPLIB class and it's generic functions lets me switch databases in the future if needed without having to rewrite the code to use the database-specific functions in PHP.
For this project I will need three files from the PHPLIB library: prepend.php3, local.inc, and db_mysql.inc. The very first thing I'll do is rename these files to prepend.php, local.php, and db_mysql.php. There are two reasons for renaming these files.
The next step is to modify local.php so that it contains a database access sub-class with
my specific mysql access information:
class remindme_db extends DB_Sql {
var $Host = "localhost";
var $Database = "remindme";
var $User = "remindme";
var $Password = "my_password";
}
Then, I'll modify the prepend.php file to remove any extra include statements for files
that I'm not using on this project:
// Modified heavily off prepend.php3 from phplib
require($DOCUMENT_ROOT . "/phplib/db_mysql.php"); /* Change this to match your database. */
require($DOCUMENT_ROOT . "/phplib/local.php");
Accessing a database through PHPLIB is very easy. Here is a quick example:
This example will print out a list of the event_description value for each reminder
in our database.
$l_db = new remindme_db;
$l_sql = "SELECT event_description FROM bday_reminders";
$l_db->query($l_sql);
while ($l_db->next_record())
echo $l_db->f("event_description") . "<BR>\n";
$l_db = new stuff_db;$l_sql = "SELECT event_description FROM bday_reminders";$l_db->query($l_sql);query() method of the database class, passing in
the SQL statement that we wish to execute.
while ($l_db->next_record())next_record() method will return FALSE when we have reached the
end of the matching records.
echo $l_db->f("event_description") . "<BR>\n";f() method returns the value of one column from the result set.
In this case we are requesting the value of the event_description column, so
we use $l_db->f("event_description") to retrieve the value.