Home > Articles > Programming > PHP

This chapter is from the book

Building a Database Abstraction Class

Databases can make it hard to create durable and transportable code. If database code is built tightly into a project it can be difficult to migrate from one database server to an other, for example.

In this sample we are going to create a basic utility class that separates a lot of the database facing code from the logic of a project as a whole. The class will broadly achieve two things. First it will present a conduit between a program and the database via which SQL queries can be passed. Second, it will automate the generation of SQL for a range of frequently performed operations, such as simple SELECT and UPDATE statements. In the case of SELECT queries, the result set will be provided in the form of an array of associative arrays.

The class should provide two main benefits for the client coder. First, in automating simple queries it should save the need to construct SQL statements on the fly. Second, in providing a clear interface to its functionality it should safeguard portability. If the project is to be moved to a different database server, then an alternative class can be written that maintains the same functionality but with a different implementation behind the scene.

It must be noted, however that all database abstraction schemes (including Perl's famous database independent interface or DBI library) suffer from one major drawback. Different database engines tend to support different SQL syntaxes and features. This means that SQL statements written to work with MySQL may not work with Oracle, for example. For simple projects you can go some way towards dealing with this problem by using SQL features that are as 'standard' as possible, and avoiding the use of features specific to a database application.

Connecting to the Database

To start with, let's build the methods to connect to a database server, and select a database. Along the way, we can look at the method we are going to use for reporting errors.

class DataLayer {
    var $link;   
    var $errors = array();
    var $debug = false;

    function DataLayer( ) {
    function connect( $host, $name, $pass, $db ) {
        $link = mysql_connect( $host, $name, $pass );
        if ( ! $link ) {
            $this->setError("Couldn't connect to database server");
            return false;

        if ( ! mysql_select_db( $db, $this->link ) ) {
            $this->setError("Couldn't select database: $db");
            return false;
        $this->link = $link;
        return true;

    function getError( ) {
        return $this->errors[count($this->errors)-1];

    function setError( $str ) {
        array_push( $this->errors, $str );

We have called our class DataLayer. We establish three properties; $link will store our database resource, $errors will store an array of error messages, and $debug is another flag which will help us to monitor the behavior of our class.

The connect() method simply uses the now familiar mysql_connect() and mysql_ select_db() functions to connect to the server and choose a database. If you implement this class yourself, you might consider storing the $host, $name, $pass and $db argument variables in class properties. We have chosen not to in this example. If we encounter any problems with connection we call the setError() function which maintains a stack of error messages. If all goes well, however, we store the database resource returned by mysql_connect in our $link property.

Making the Query

We're now ready to build the query methods. We split these up into three:

    function _query( $query ) {
        if ( ! $this->link ) {
            $this->setError("No active db connection");
            return false;
        $result = mysql_query( $query, $this->link );
        if ( ! $result )
            $this->setError("error: ".mysql_error());
        return $result;

    function setQuery( $query ) {
        if (! $result = $this->_query( $query ) )
            return false;
        return mysql_affected_rows( $this->link );

    function getQuery( $query ) {
        if (! $result = $this->_query( $query ) )
            return false;
        $ret = array();
        while ( $row = mysql_fetch_assoc( $result ) )
            $ret[] = $row;
        return $ret;

_query() performs some basic checks, but all it really does is to pass a string containing an SQL query to the mysql_query() function, returning a mysql result resource if all goes well. Both setQuery() and getQuery() call _query(), passing it an SQL string. They differ in what they return to the user, however. setQuery() is designed for SQL statements that act upon a database. UPDATE statements, for example. It returns an integer representing the number of affected rows. getQuery() is designed primarily for SELECT statements. It builds an array of the result set which it returns to the calling code. We're now in a position to test our class.

Testing the Basic Class

For the test, we assume the presence of a table called test_table. The CREATE statement illustrates its structure:

      CREATE TABLE test_table (
           PRIMARY KEY( id ),
           name VARCHAR(255),
           age INT,
           description BLOB

Our test code simply connects to the database, adds some data, and then requests it back again, looping through the returned array and printing an HTML table to the browser.

$dl = new DataLayer( );
$dl->connect( "localhost", "", "", "test" ) or die ( $dl->getError() );
$dl->setQuery("DELETE FROM test_table");
$dl->setQuery("INSERT INTO test_table (name, age, description) 
        VALUES('bob', 20, 'student')");
$dl->setQuery("INSERT INTO test_table (name, age, description) 
        VALUES('mary', 66, 'librarian')");
$dl->setQuery("INSERT INTO test_table (name, age, description) 
        VALUES('su', 31, 'producer')");
$dl->setQuery("INSERT INTO test_table (name, age, description) 
        VALUES('percy', 45, 'civil servant')");
$table = $dl->getQuery("SELECT * from test_table");

print "<table border=\"1\">";
foreach( $table as $d_row ) {
    print "<tr>";
    foreach ( $d_row as $field=>$val )
        print "<td>$val</td>";
    print "</tr>";
print "</table>";

Automating SQL Statements

SQL can be a highly complex affair, and it is not our purpose to reinvent it. However, some fairly basic operations are performed over and over again, SQL statements can be tedious to construct within a script. These methods should simplify some of these tasks.

Let's illustrate the technique by looking at a method for automating basic SELECT statements.

    function select( $table, $condition="", $sort="" ) {
        $query = "SELECT * FROM $table";
        $query .= $this->_makeWhereList( $condition );
        if ( $sort != "" )
            $query .= " order by $sort";
        $this->debug( $query );
        return $this->getQuery( $query, $error );
    function _makeWhereList( $condition ) {
        if ( empty( $condition ) )
            return "";
        $retstr = " WHERE ";
        if ( is_array( $condition ) ) {
            foreach( $condition as $field=>$val )
                array_push( $cond_pairs, "$field=".$this->_quote_val( $val ) );
            $retstr .= implode( " AND ", $cond_pairs );
        } elseif ( is_string( $condition ) && ! empty( $condition ) )
            $retstr .= $condition;
        return $retstr;

The select() method requires at least a table name. It will also optionally accept condition and sort arguments. The sort argument should be a string such as "age DESC, name". The condition argument can be either an associative array or a string. A condition passed as an associative arrays will be used to construct a WHERE clause with the keys representing field names. So

array( name=>"bob", age=>20 )

will resolve to

WHERE name='bob' AND age=20

Where more complex conditions are required, such as

WHERE name='bob' AND age<25

the condition argument should be passed as string containing the valid SQL fragment. The construction of the WHERE clause takes place in the _makeWhereList() method. If no condition is required an empty string is returned. If the condition is a string, it is simply tacked onto the string "WHERE" and returned. If the condition is an array however, the fieldname/value pairs are first constructed and stored in an array called $cond_pairs. The implode() function is then used to join the new array into a single string, the fieldname/value pairs separated by the string " AND ".

Notice that we call a utility method called quote_val() when we are building our string. This is used to add backslashes to special characters (such as single quotes) within values. It also surrounds strings in quotes, though it leaves numbers alone.

    function _quote_val( $val ) {
        if ( is_numeric( $val ) )
            return $val;
        return "'".addslashes($val)."'";

The addslashes() function built-in to PHP. It accepts a string and returns another with special characters backslashed. This is useful for us, because we must surround strings sent to MySQL with single quotes.

To get an array containing a complete listing of our table we can now use the select() method.

$table = $dl->select("test_table");

To get all rows with an age of less than 40:

$table = $dl->select("test_table", "age<40");

To pull out information about people called bob

$table = $dl->select("test_table", array('name'=>"bob") );

Bringing It All Together

Listing 12.7 represents the complete DataLayer class. It includes the methods update(), delete(), and insert() that are similar to select() in that they simply construct SQL statements.

Listing 12.7 The DataLayer Class

 1: <?
 2: class DataLayer {
 3:   var $link;  
 4:   var $errors = array();
 5:   var $debug = false;
 7:   function DataLayer( ) {
 8:   }
 10:   function connect( $host, $name, $pass, $db ) {
 11:     $link = mysql_connect( $host, $name, $pass );
 12:     if ( ! $link ) {
 13:       $this->setError("Couldn't connect to database server");
 14:       return false;
 15:     }
 17:       if ( ! mysql_select_db( $db, $link ) ) { 
 18:       $this->setError("Couldn't select database: $db");
 19:       return false;
 20:     }
 21:     $this->link = $link;
 22:     return true;  
 23:   }
 25:   function getError( ) {
 26:     return $this->errors[count($this->errors)-1];
 27:   }
 29:   function setError( $str ) {
 30:     array_push( $this->errors, $str );
 31:   }
 33:   function _query( $query ) {
 34:     if ( ! $this->link ) {
 35:       $this->setError("No active db connection");
 36:       return false;
 37:     }
 38:     $result = mysql_query( $query, $this->link );
 39:     if ( ! $result )
 40:       $this->setError("error: ".mysql_error());
 41:     return $result;
 42:   }
 44:   function setQuery( $query ) {
 45:       if (! $result = $this->_query( $query ) ) 
 46:       return false;  
 47:     return mysql_affected_rows( $this->link );
 48:   }
 50:   function getQuery( $query ) {
 51:       if (! $result = $this->_query( $query ) ) 
 52:       return false;  
 53:     $ret = array();
 54:     while ( $row = mysql_fetch_assoc( $result ) )
 55:       $ret[] = $row;
 56:     return $ret;
 57:   }
 59:   function getResource( ) {
 60:     return $this->link;
 61:   }
 63:   function select( $table, $condition="", $sort="" ) {
 64:         $query = "SELECT * FROM $table";
 65:     $query .= $this->_makeWhereList( $condition );  
 66:     if ( $sort != "" )
 67:       $query .= " order by $sort";
 68:     $this->debug( $query );
 69:         return $this->getQuery( $query, $error );
 70:   }
 72:   function insert( $table, $add_array ) {
 73:         $add_array = $this->_quote_vals( $add_array );
 74:         $keys = "(".implode( array_keys( $add_array ), ", ").")";
 75:         $values = "values (".implode( array_values( $add_array ), ", ").")";
 76:         $query = "INSERT INTO $table $keys $values";
 77:     $this->debug( $query );
 78:         return $this->setQuery( $query );
 79:   }
 81:   function update( $table, $update_array, $condition="" ) {
 82:     $update_pairs=array();
 83:     foreach( $update_array as $field=>$val )
 84:       array_push( $update_pairs, "$field=".$this->_quote_val( $val ) );
 86:         $query = "UPDATE $table set ";
 87:     $query .= implode( ", ", $update_pairs );
 88:     $query .= $this->_makeWhereList( $condition );  
 89:     $this->debug( $query );
 90:         return $this->setQuery( $query );
 91:   }
 93:   function delete( $table, $condition="" ) {
 94:         $query = "DELETE FROM $table";
 95:     $query .= $this->_makeWhereList( $condition );  
 96:     $this->debug( $query );
 97:         return $this->setQuery( $query, $error );
 98:   }
100:   function debug( $msg ) {
101:     if ( $this->debug )
102:       print "$msg<br>";
103:   }
105:   function _makeWhereList( $condition ) {
106:     if ( empty( $condition ) )
107:       return "";
108:     $retstr = " WHERE ";
109:     if ( is_array( $condition ) ) {
110:       $cond_pairs=array();
111:       foreach( $condition as $field=>$val )
112:         array_push( $cond_pairs, "$field=".$this->_quote_val( $val ) );
113:       $retstr .= implode( " and ", $cond_pairs );
114:     } elseif ( is_string( $condition ) && ! empty( $condition ) )
115:       $retstr .= $condition;
116:     return $retstr;
117:   }
119:   function _quote_val( $val ) {
120:     if ( is_numeric( $val ) )
121:       return $val;
122:     return "'".addslashes($val)."'";
123:   }
125:   function _quote_vals( $array ) {
126:     foreach( $array as $key=>$val )
127:       $ret[$key]=$this->_quote_val( $val );
128:     return $ret;
129:   }
130: }  
131: ?>

As you should see from the code, update() (line 81), delete() (line 93), and insert() (line 72) provide a similar interface to that provided by select() (line 63).

update() which is declared on line 81 requires a string representing the table to be worked with. It also requires an associative array of keys and values. The keys should be the field name to be altered, and the value should be the new content for the field. Finally, an optional condition argument is accepted. This follows the same logic as the condition argument in the select() method. It can be a string or an array.

delete() which is declared on line 93 requires a table name, and an optional condition argument.

insert() is declared on line 72 and requires a table name, and an associative array of fields to add to the row. The keys should be the field name to be altered, and the value should be the new content for the field.

We had better see the code in action. Listing 12.8 is a simple test script that populates and manipulates a table in a database.

Listing 12.8 Working with the DataLayer Class

 1: <html>
 2: <head>
 3: <title>Listing 12.8 Working with the DataLayer Class</title>
 4: </head>
 5: <body>
 6: <?php
 7: include("listing12.9.php");
 8: $people = array( 
 9:   array( 'name'=>"bob", 'age'=>20, 'description'=>"student" ),
10:   array( 'name'=>"mary", 'age'=>66, 'description'=>"librarian" ),
11:   array( 'name'=>"su", 'age'=>31, 'description'=>"producer" ),
12:   array( 'name'=>"percy", 'age'=>45, 'description'=>"civil servant" )
13:   );
15: $dl = new DataLayer( );
16: $dl->debug=true;
17: $dl->connect( "localhost", "", "", "test" ) or die ( $dl->getError() );
19: $dl->delete( "test_table" );
21: foreach ( $people as $person ) {
22:   $dl->insert( "test_table", $person ) or die( $dl->getError() );
23: }
25: foreach ( $people as $person ) {
26:   $person['age']++;
27:   $dl->update( "test_table", $person, array( 'name'=>$person['name'] ) );
28: }
30: $dl->delete( "test_table", "age < 25" );
31: $table = $dl->select( "test_table" );
33: print "<table border=\"1\">";
34: foreach( $table as $d_row ) {
35:   print "<tr>";
36:   foreach ( $d_row as $field=>$val )
37:     print "<td>$val</td>";
38:   print "</tr>";
39: }
40: print "</table>";
41: ?>
42: </body>
43: </html>

We initialize our data using an associative array beginning on line 8. We instantiate a DataLayer object on line 15, set the object's $debug property to true on line 16, and connect to the database on line 17. Because the object is in debug mode, all the SQL we generate will be output to the browser after being sent to the database.

We call the delete() method on line 19, to clear any data in the table, before populating it by looping through our $people on line 21 array and calling the insert() method (line 22) for each person. DataLayer is designed to work with associative arrays, so we only need to pass each element of the $people array to insert() in order to populate the table.

We then decide that we wish to alter the age field of each row. Once again we loop through the people array (line 25), incrementing each element before calling update() on line 27. We can pass the entire $person array to update(). Although this will mean that most fields in the row will be updated with their own value, this is quick and easy from the client coder's perspective. The third argument to update() is a condition array containing the name key and value. In a real world example we would probably use the id field to ensure that we are updating only one row.

Finally, we call delete() once again (line 30), this time including a condition argument. Because we wish to delete all rows with an age value of less than 25, we pass a condition string rather than an array. Remember that condition arrays are only useful for demanding equivalence, so we must 'hardcode' the 'less then' comparison into a string.

You can see the output from Listing 12.8 in Figure 12.1. Because the object was in debug mode, notice that the SQL has been output to the browser.

Figure 12.1 Working with the DataLayer Class.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020