Object-Oriented Connection Class in PHP

I started out in professional web development by using ASP.NET, so I was spoiled by the fact that Microsoft offers a SqlConnection class to use for various database related connectivity features. When I started with PHP, I decided to do some research and write a similar (albeit, much simpler) Connection class. Keep in mind that this class example only supports MySQL.

I started by defining some members of this class and came up with six useful members.

  • Database connection object returned from mysql_connect
  • Boolean to determine if the connection is currently open or closed
  • Database server host name
  • Database catalog name
  • Database user
  • Database password

In order to use this class, we need to add a constructor. I began by creating a default constructor that simply initializes values of the member properties. Take notice that not all of the properties are initialized by the default constructor. $dbConnection is not initialized until the Open() method is called and $isConnectionAlive is already false by default.

Now that the class can be instantiated, we need to add methods to allow operations. Below are the two methods that will perform the opening of the database connection and the closing of the database connection. Refer to the comments inline to understand what is happening.

That’s it! This is now a fully functional database connection class that allows for instantiation with opening and closing behaviors. See below for an example of its use. Note that the below example is not contained in the Connection.class.php file and is instead located in some other page that will be instantiating a Connection object.

The cool thing is that this class can be expanded to work with other databases.

One thought on “Object-Oriented Connection Class in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *