Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

An Introduction to Object Oriented PHP – Part 3

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!

  1. Variables and Constructor
  2. Main Functions
  3. 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.

Wordpress.com stats not installed! Posted Thursday, July 30th, 2009 / Back to Top

I this post. Tweet
SPONSOR

22 Comments 6 Mentions

  1. Chukki Author Editor

    Very nice job! I love the OOP Series… because its a hole in my skills…! More like this ;)

    July 31, 2009 · Reply

  2. Paratron Author Editor

    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 31, 2009 · Reply

  3. Jenna Author Editor

    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 31, 2009 · Reply

  4. Jack Franklin Author Editor

    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 31, 2009 · Reply

  5. emilien Author Editor

    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 31, 2009 · Reply

  6. Phunky Author Editor

    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 31, 2009 · Reply

  7. GiN Author Editor

    Jack Franklin is right. But Phunky is not. Because use a magic methods is not a best way.
    .-= GiN´s last blog ..Что делать если усы и борода мешают партнеру? =-.

    July 31, 2009 · Reply

  8. Martin Bean Author Editor

    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 31, 2009 · Reply

  9. Benjamin Reid Author Editor

    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 31, 2009 · Reply

  10. Cody Robertson Author Editor

    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.

    July 31, 2009 · Reply

  11. kodegeek Author Editor

    Nice Post. Love OOP as well.

    August 1, 2009 · Reply

  12. Karol Sójko Author Editor

    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 =-.

    August 6, 2009 · Reply

  13. ivicta Author Editor

    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 5, 2009 · Reply

  14. Dixon Crews Author Editor

    @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/ =-.

    November 5, 2009 · Reply

  15. Data Skull Author Editor

    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.

    December 3, 2009 · Reply

  16. malisa Author Editor

    hey thanx for an informative tutorial ….helped a lot

    January 17, 2010 · Reply

  17. Jason Davis Author Editor

    I love the site, keep up the great work! Another note, the use of
    var $host; is the depreciated way of doing it, you should use public/private $host; instead.

    January 8, 2011 · Reply

  18. Thinkers Author Editor

    Hi
    Good post.
    But could you (or any one) please send me this code in zip format. In fact I am a beginner and having a lot of problems to use this code in my project.

    February 5, 2012 · Reply

  19. Nathaniel Author Editor

    This introduction is very detail, thank you.

    February 25, 2012 · Reply

  20. Free Logo Design Author Editor

    The functions described are informative. This is well organized and resourceful tutorial about php.

    June 1, 2012 · Reply

  21. Free Vactor Download Author Editor

    This site is informative and guide to solve our probem

    June 4, 2012 · Reply

  22. nish Author Editor

    how wud u pass values to insert function..

    August 22, 2012 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top