Viewed   144 times

I have been using the procedural approach with mysql* until recently. Now I want to shift to mysqli and object oriented approach. Many online resources and books state that OOP is better than procedural even in case of PHP. After going through some online tutorials, I have written a small program that connects to the database and selects a value. I want to know why the object oriented approach is better? Plus is this the right way to code an OO php web page?

The object oriented approach

$host = "localhost";
$username = "root";
$password = "";
$dbname = "compdb";

@ $db = new mysqli($host, $username, $password, $dbname);

    die("Connection could not be established");

$query = "SELECT company_id FROM company_basic_details WHERE company_name = 'ABC'";
$result = $db->query($query);

$total_num_rows = $result->num_rows;

echo "The Results Are : <br>";

while($row = $result->fetch_array())
    echo $row['company_id'];

The procedural approach


$host = "localhost";
$username = "root";
$password = "";
$dbname = "compdb";

@ $db = mysqli_connect($host, $username, $password, $dbname);

    die("Connection could not be established");

$query = "SELECT company_id FROM company_basic_details WHERE company_name = 'ABC'";
$result = mysqli_query($db, $query);

$total_num_rows = mysqli_num_rows($result);

echo "The Results Are : <br>";

while($row = mysqli_fetch_array($result))
    echo $row['company_id'];



The main reason is that PHP is moving steadily in the direction of OO programming.

There's nothing wrong with using mysqli_xxx() functions rather than the OOP equivalents; it is exactly the same as far as the code is concerned.

The only issue is that you'll be getting yourself further and further behind the curve in terms of what people think of as well-written PHP code.

It's worth noting that the PDO library, which is considered the ideal for most DB code in PHP is OOP-only. It doesn't have a procedural interface. And nor do most of the other new features added to PHP in the last few versions. If you want to use PHP to its fullest, you need to know OOP anyway.

There's also the point about the ability to create an extension class for your DB -- something like this:

class myDB extends mysqli {
     .... your own stuff here to extend and improve the base mysqli class

Of course you can achieve the same thing with procedural code, but it's not as neat as the OOP way. And of course that's only relevant if you actually want to extend the class.

However, as a first step, just moving from mysql_xxx() to mysqli_xxx() is a great start. Moving the whole way to using the OOP interface would be even better, but just switching to the mysqli functions is a good start.

Using the procedural interface to begin with will certainly make the transition away from the old mysql_xx() functions easier, so if switching to the OOP interface is too much of a leap at the beginning, don't feel you have to do it all in one go. Start with a conversion to the procedural mysqli functions, then switch to the OOP methods later on; neither jump will be that big on its own.

Saturday, August 27, 2022

What is the point in using object-oriented programming when you cannot find good reasons or motivation to do so?

You must be motivated by the need to conceive and manipulate ideas as objects. There are people who feel the need to be perceptive of concepts, flow or functions rather than objects and they are then motivated towards programming oriented towards concepts, ideas, or functional flow.

Some 13 years ago, I switched to c++ from c simply because there were ideas I needed but c would not easily perform. In short, my need motivated my programming oriented towards objects.

The object-oriented mind-set

First, you have bytes, chars, integers and floats.

Then your programme starts being cluttered with all kinds of variables, local and static. Then you decide to group them into structs because you figured that all the variables which are commonly passed around.

Conglomeration of data

So like printer's info should have all its variables enclosed into the Printer struct:

{id, name, location,
  manufacturer, networkAddr},

So that now, when you call function after function over printer info, you don't have functions with a long list of arguments or a large collection of static variables with huge possibilities of cross-talk.

Incorporation of information

But data conglomeration is not good enough. I still have to depend on a bunch of functions to process the data. Therefore, I had a smart idea or incorporating function pointers into the Printer struct.

{id, name, location,
 manufacturer, networkAddr,
 *print(struct printer),
 *clean(struct printer)

Data graduates into information when data contains the processes on how to treat/perceive the data.

Quantization of information

Now laser, ribbon and inkjet printers do not all have the same set of information but they all have a most common set of denominators (LCD) in information:

Info common to any printer: id, name, location, etc

Info found only in ribbon printers: usedCycles, ribbon(fabric|cellophane), colourBands, etc

Info found only in inkjet: ink cartridges, etc

Info found only in lasers: ...

For me and many object-oriented cohorts, we prefer to quantize all the common info into one common information encapsulation, rather than define a separate struct/encapsulation for each printer type.

Then, we prefer to use a framework which would manage all the function referencing for each type of printer because not all printers print or are cleaned the same way.

So your preference/motivation oriented away from objects is telling you that your programming life is easier if you do not use objects? That you prefer to manage all those structural complexities yourself. You must not have written enough software to feel that way.

The necessity of laziness

Some people say - necessity is the mother of creativity. (as well as, Love of money is the root of evil).

But to me and my cohorts - laziness in the face of necessity are the parents of creativity. (as well as the lack of money is the other parent of evil).

Therefore, I urge you to adopt a lazy attitude towards programming so that the principle of the shortest path would kick into your life and you'll find but have no other choice than to graduate towards orienting yourself towards programming with objects.

Wednesday, August 24, 2022

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() {
            $_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

Saturday, August 20, 2022

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.


void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)


The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.


auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int


Prefer {} initialization over alternatives unless you have a strong reason not to.

Tuesday, November 22, 2022

Here's good article discussing the issue. I also have seen some anecdotal bench-marks that will put OOP PHP overhead at 10-15% Personally I think OOP is better choice since at the end it may perform better just because it probably was better designed and thought through. Procedural code tends to be messy and hard to maintain. So at the end - it has to be how critical is performance difference for your app vs. ability to maintain, extend and simply comprehend

Friday, November 25, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :