Asked  2 Years ago    Answers:  5   Viewed   139 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

You can test procedural code with PHPUnit. Unit tests are not tied to object-oriented programming. They test units of code. In OO, a unit of code is a method. In procedural PHP, I guess it's a whole script (file).

While OO code is easier to maintain and to test, that doesn't mean procedural PHP cannot be tested.

Per example, you have this script:


$arg1 = $_GET['arg1'];
$arg2 = $_GET['arg2'];
$return = (int)$arg1 + (int)$arg2;
echo $return;

You could test it like this:

class testSimple_add extends PHPUnit_Framework_TestCase {

    private function _execute(array $params = array()) {
        $_GET = $params;
        include 'simple_add.php';
        return ob_get_clean();

    public function testSomething() {
        $args = array('arg1'=>30, 'arg2'=>12);
        $this->assertEquals(42, $this->_execute($args)); // passes

        $args = array('arg1'=>-30, 'arg2'=>40);
        $this->assertEquals(10, $this->_execute($args)); // passes

        $args = array('arg1'=>-30);
        $this->assertEquals(10, $this->_execute($args)); // fails


For this example, I've declared an _execute method that accepts an array of GET parameters, capture the output and return it, instead of including and capturing over and over. I then compare the output using the regular assertions methods from PHPUnit.

Of course, the third assertion will fail (depends on error_reporting though), because the tested script will give an Undefined index error.

Of course, when testing, you should put error_reporting to E_ALL | E_STRICT.

Sunday, November 20, 2022

While how you code is entirely your decision and unique style, I'd say there are a few factors to consider when deciding on procedural, object oriented, or mixed.

Program specifications -

Primarily, if you are on a team, writing the program for someone else, or following your own specifications, consider whether or not the choice has already been made.

Availability -

Let's face it. Sometimes the best libraries are available in either object oriented or procedural, and not both. In such a case, changing from one style would require using a completely different library, or building a class or function library yourself. An available library may save you time, with the only offset cost being a procedural function in a primarily object oriented program, or vice versa.

Familiarity -

Similar to availability, you may be more familiar with a certain class or set of functions. While you may have time to stop and learn a new class module to add to your knowledge, you may be able to save time by using a procedural library that you've already learned and thoroughly tested. So if you are working on a timeline, you may want to go with the more familiar library. However, if you are researching and learning, then you may want to take the time to read documentation, install, and test a new solution.

Data handling and speed -

One more factor to muse about is how are you handling the data. If the data is within the class, then the class will likely have methods to operate on the data. In such a situation, procedural programming would require obtaining the data from the class or object, operating on the data, and then updating the object. A better design would be to include the function in the object in my opinion.

However, if all of your data handling is outside of the class, then using a function may be faster. If you wanted to use a class method, you would have to load the class, and possibly create an object. Even static methods may be slower than a function. So if speed is a consideration, such as in a loop, then consider how many steps your program and PHP has to go through to get to the function, class, or object.

Looking ahead -

If you are wanting to select between procedural or object-oriented programming, then try to predict what will be most useful in the future. I've found object-oriented programming to be very useful for creating reusable code. I've found procedural programming to be very useful for command line code and organizing and using objects. It's likely these will stay the same as computer science evolves, and so work I've done previously is more likely to be useful again.

In contrast, some libraries and programming languages may encourage a style. PHP supports both styles. But if my overall impression is accurate, then PHP has been moving in the direction of object-oriented styles. If selecting between PHP functions and objects, look and see what version of PHP the functions were created for. Also check to see if any of the procedural functions are depreciated or going to become obsolete. If so, use the object-oriented approach, as this will make your program more useful when those procedural functions are no longer supported.

Hope this provides some considerations. Thanks.

Tuesday, October 25, 2022

$stmt->bind_param() requires all params to be passed by reference, so you can't pass function's return value directly (without assigning it to a variable first, that is). But, as was already mentioned in the comments, you don't need to escape the parameters at all, that's one of the advantages of using prepared statements.

Wednesday, November 23, 2022

I assume that you're running this on a Retina device. In UIGraphicsBeginImageContextWithOptions, you asked for the default scale, which is the scale of the main screen, which is 2. This means that it's generating a bitmap 4x as large. In the second function, you're drawing at 1x scale.

Try passing a scale of 1 to UIGraphicsBeginImageContextWithOptions and see if your performance is similar.

Wednesday, October 5, 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 :

Browse Other Code Languages