Question

Is there a significant difference in using an object oriented approach over a procedural approach when implementing mysql in php? On the php website about mysqli_query, (http://www.php.net/manual/en/mysqli.query.php), it provides an example of both, and I just want to know if there is any significant performance difference, or just know when to use each of them.

Was it helpful?

Solution

The answer to which one is better is "it depends." As with anything, there are a variety of different approaches and you should also keep in mind that code that uses objects is not necessarily object oriented but can still be written procedurally. In the same vein, code that does not use objects can still be modular.

I would choose to use the mysqli class every time, though. There is no significant difference in performance. You probably won't realize some of the advantages of using a DB class such as simplified polymorphism, so my only argument for using the class is that I prefer the syntax. However, rather than use mysqli directly I would probably recommend that you extend or compose it. You can only do this with the class.

class DB extends mysqli {
    public function __construct() {
        parent::__construct($_SERVER['DB_HOST'],
            $_SERVER['DB_USER'], $_SERVER['DB_PASS']);
    }
}

This is a very shallow example.

An example of the polymorphism I was talking about above would be something like this:

class User implements DAO {
    private $db;
    public function __construct(DB $db) {
        $this->db = $db;
    }
}

//Testing code is simplified compared to using it in production
class TestDB extends DB {}
new User(new TestDB);
new User(new DB);

By the way I categorically prefer PDO over mysqli

OTHER TIPS

As you are an intern it would be advisable to find out who is going to maintain the code in the future.

  1. Nobody in company.Go with OOP ,if you are happy with this, as OOP is the current practice.
  2. In House. Go with current practice,hopefully OOP

Nope, there is no difference.

But you're overlooking way more important thing: no raw mysqi API functions have to be used in the application code, neither OOP or procedural.

There is one thing unknown to PHP users: API calls aren't intended to be used as is. They have to be wrapped in some sort of library. Without it mysqli is just a pain in the back, it require 2 times more code than old good mysql ext.

So, it does matter if you are using such a layer, but it doesn't matter if it is written using procedural or OOP inside.

Yet this library ought to be built in the form of class. There is just no other way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top