Home arrow PHP arrow Page 2 - Object Interaction in PHP: Introduction to Aggregation, part 4

Assembling classes: a brief look at the “MySQLConnector” class - PHP

In the fourth and final article in our series covering aggregation in PHP, Alejandro Gervasio reviews the MySQLConnector and Pager classes. He then uses these classes first to build a simple database, then to display some paged results from the database.

  1. Object Interaction in PHP: Introduction to Aggregation, part 4
  2. Assembling classes: a brief look at the “MySQLConnector” class
  3. Assembling classes (continued): the “Pager” class at glance
  4. Putting the classes to work: a practical example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 23
June 15, 2005

print this article



As most developers want to move quickly to the nitty-gritty of the source code, let’s show the whole list for our first class. Here’s how it looks:

class MySQLConnector {

            var $conId; // connection identifier

            var $host; // MySQL host

            var $user; // MySQL username

            var $password; // MySQL password

            var $database; // MySQL database

            var $result; // result set

            // constructor

            function MySQLConnector($host,$user,$password,$database){

                        // validate incoming parameters

                        (!empty($host))?$this->host=$host:die('Host parameter not valid');

                        (!empty($user))?$this->user=$user:die('User parameter not valid');

                        (!empty($password))?$this->password=$password:die('Password parameter not valid');

                        (!empty($database))?$this->database=$database:die('Database parameter not valid');

                        // connect to MySQL and select database



            // connect to MYSQL server and select database

            function connectDB(){

                        $this->conId=@mysql_connect($this->host,$this->user,$this->password) or die('Error connecting to the server '.mysql_error());

                        @mysql_select_db($this->database,$this->conId) or die('Error selecting database');


            // perform query

            function performQuery($query){

                        $this->result=@mysql_query($query,$this->conId) or die('Error performing query '.$query);


            // fetch row

            function fetchRow(){

                        return mysql_fetch_array($this->result,MYSQL_ASSOC);


            // get number of rows

            function getNumRows(){

                        return mysql_num_rows($this->result);


            // get number of affected rows

            function getAffectedRows(){

                        return mysql_affected_rows($this->conId);


            // get ID from last inserted row

            function getInsertID(){

                        return mysql_insert_id($this->conId);



I hope that the above listed code refreshed your memory, because it’s been a while since the last time we reviewed this class. Taking a quick look at its definition, we can see that the class shows a few simple methods for connecting to the MySQL server, performing SQL queries, returning table rows and so forth. Also, as mentioned earlier, it presents some methods for calculating the number of rows returned by a query, as well as the rows affected by an INSERT, UPDATE or DELETE query.

Indeed, the class is easily extendable, either by adding new methods according to specific needs, or deriving a subclass, which will inherit all of the methods present in it, by adding more capacity to those present in the base class. The preferred approach will depend on your personal needs.

Fortunately, the advantage of having a set of functional classes is that they can be used as standalone packages or easily plugged into other applications. In this case, let us say we need to use this class to quickly fetch some records. Here’s a quick and dirty implementation to extract some records from a “users” table:

// include the class

require_once 'mysqlclass.php';

// instantiate a MySQLConnector object passing to it the connection parameters

$db=&new MySQLConnector('host','user','password','database');

// build the query

$sql='SELECT fname,lname FROM users';

// perform query


// display the results


            echo 'First Name :'.$row['fname'].' Last Name :'. $row['lname'].'<br />';


// display total number of results

echo 'Total number of results :'.$db->getNumRows();

The above example shows how easy it is to use the class to perform some of the most common operations associated with MySQL. We instantiated a new “MySQLConnector” class, then performed a simple “SELECT" statement to retrieve records from a hypothetical “users” table, displaying the “firstname” and “lastname” fields included in each table row. After displaying the results, we indicated the total number of rows returned by the query. It's simple and straightforward.

Now that we’ve gained a more intimate knowledge of the functionality of this class, let’s take the next step, and list the complete source code for the “Pager” class. Just keep reading.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: