An Introduction to Object Oriented PHP – Part 3

Introduction
Welcome to the third and final part of a series introducing Object Oriented PHP! Please, as I have urged before, go back and read parts one and two if you have not already, the basics are the most important part!
In this Tutorial
Today, we are going to finally complete the task that we’ve been leading up to: writing our MySQLi DB class! We’re going to be using everything we’ve learned so far to do this, so strap in and enjoy!
- Variables and Constructor
- Main Functions
- Some extra goodies
Variables and Constructor
Create a new file called class.db.php and insert the following:
<?php
/*
* class db
* @param Host
* @param User
* @param Password
* @param Name
*/
class db
{
var $host; //MySQL Host
var $user; //MySQL User
var $pass; //MySQL Password
var $name; //MySQL Name
var $mysqli; //MySQLi Object
var $last_query; //Last Query Run
/*
* Class Constructor
* Creates a new MySQLi Object
*/
function __construct($host, $user, $pass, $name)
{
$host = $this->host;
$user = $this->user;
$pass = $this->pass;
$name = $this->name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
}
$db = new db('localhost', 'root', '', 'blog');
?>**Try and dissect what we have done here before reading the explanation!**
First, we have done the most important part of Object Oriented PHP – organization! We have said what the class name is, and all the parameters that need to be passed to it when it is loaded. Next, inside the class, we have defined our four variables for MySQL connection and then required them as parameters of the constructor function, which can be passed when the class is loaded at the bottom of the file. Next, we have set our $mysqli variable to a new MySQLi Object. Simple, right? Let’s move on.
Main Functions
SELECT
Now that we have the connection down, we can start working with the database. Add a select function like this:
/*
* Function Select
* @param fields
* @param from
* @param where
* @returns Query Result Set
*/
function select($fields, $from, $where)
{
$query = "SELECT " . $fields . " FROM `" . $from . "` WHERE " . $where;
$result = $this->mysqli->query($query);
$this->last_query = $query;
return $result;
}Here we have made a select function for selecting data from a MySQL table. We have defined three parameters, and you can see how they fit into the final query. All we return from this function is a query result set, which you can work with however you like in your pages.
INSERT
Of course, we can select data with our class now, but we don’t have anything to select unless we insert it! Let’s do that now by adding this function to your class:
/*
* Function Insert
* @param into
* @param values
* @returns boolean
*/
function insert($into, $values)
{
$query = "INSERT INTO " . $into . " VALUES(" . $values . ")";
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}Another quite simple function, we are just requiring two parameters: the table name to insert the data into, and the values for the fields. Instead of returning any real data for this function, we just go ahead and run it and if it inserted the data, it returns true, and if not, false. Simple for inserting data.
DELETE
Now that we can insert and then select our data, we have to have a way to delete it say if a user wanted to delete their account. Add this function:
<?php
/*
* Function Delete
* @param from
* @param where
* @returns boolean
*/
function delete($from, $where)
{
$query = "DELETE FROM " . $from . " WHERE " . $where;
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
?>Some extra goodies
You probably noticed the last_query variable we defined at the beginning of the class, then we set it every time we ran a query in a function. This is very vital for troubleshooting, to see what’s wrong with your query. Another possible class variable could be a last_error, that would hold the last error returned.
Conclusion
This will conclude this series on Object Oriented PHP – I hope you’ve at least learned the basics so you’ll be able to power up your applications! Thanks for reading.














Discussion
July 31st, 2009 at 2:46 AM
Very nice job! I love the OOP Series… because its a hole in my skills…! More like this ;)
July 31st, 2009 at 3:47 AM
I prefer to give the “Insert” Function an assoziative array and it has to build the MySQL-Insert String for itself. Thats way clearer, as one often gets confused by complex Insert Actions!
You can have a look at an example class here -> http://parastudios.de/labs/gear/pmysql.php.txt
(Look for the function makeSqlValueString() at the bottom).
Sorry, the documentation is in german ;)
July 31st, 2009 at 4:34 AM
In your __construct() shouldn’t it be ‘$this->host = $host;’ etc. instead of ‘$host = $this->host;’?
.-= Jenna´s last blog ..JJenZz: RT: @chillyjames: Lunascape – world’s first triple engine browser http://bit.ly/Mp7hP =-.
July 31st, 2009 at 4:43 AM
Your construct function (I think) is wrong:
$host = $this->host;
$user = $this->user;
$pass = $this->pass;
$name = $this->name;
Should it not be the other way round?
July 31st, 2009 at 5:49 AM
I think your class is too specific. It must be a factory patern to contruct a db abstraction layer with abstract method. I can’t use your class to make a db mysql class… You have to create other class named db_Sqli or db_Mysql for that… It’s the real goal of oop…
July 31st, 2009 at 6:08 AM
Use of magic methods such as __get() and __set() would be ideal within you __construct() which would allow you to __set(‘host’, $host);
.-= Phunky´s last blog ..Did i forget something? =-.
July 31st, 2009 at 6:24 AM
Jack Franklin is right. But Phunky is not. Because use a magic methods is not a best way.
.-= GiN´s last blog ..Что делать если усы и борода мешают партнеру? =-.
July 31st, 2009 at 6:26 AM
Jenna beat me to it: your __construct() method is wrong because you should be assigning the method’s passed arguments to the class’s properties, but you have it doing it the other way around, overriding the class’s properties with your __construct() method’s arguments.
July 31st, 2009 at 7:38 AM
Nicely explained. I was working on a database class myself the other day that’s very similar!
.-= Benjamin Reid´s last blog ..Quick Tip #5 – A ‘Hello world’ introduction to PHP classes =-.
July 31st, 2009 at 10:11 AM
Hmm, you seem to go a bit far on user friendlyness.
I always define my variables then just user the construct function to connect to mysql.
Then again, it should be,
$this->host = $host;
etc.
August 1st, 2009 at 4:37 AM
Nice Post. Love OOP as well.
August 6th, 2009 at 3:00 PM
It is always a good practice to make prepared statements and then bind the parameters, as all data coming from users should be treated as tainted.
Good work with the blog,
Cheers :)
.-= Karol Sójko´s last blog ..Ubuntu tutorial: How to install Tweetdeck on Ubuntu 9.04 64 bit =-.
November 5th, 2009 at 9:23 AM
wrong !
it’s :
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->name = $name;
not
$host = $this->host;
$user = $this->user;
$pass = $this->pass;
$name = $this->name;
November 5th, 2009 at 10:54 AM
@ivicta – It works either way.
.-= Dixon Crews´s last blog ..dixoncrews: Is it me or is Verizon getting a *little* cocky? http://phones.verizonwireless.com/motorola/droid/ =-.
December 3rd, 2009 at 2:05 PM
This database class needs a lot of work, but it is a good introduction to OOP PHP. Without the DB class I currently use in my projects I would be lost. It’s amazing how many lines of code a DB class will remove.
January 17th, 2010 at 4:56 AM
hey thanx for an informative tutorial ….helped a lot
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.