Kishan Rajdev
Kishan Rajdev

Reputation: 1965

PHP optimize sql calls

There is 1 function in my application which is getting called multiple times. Every time it returns the same result. On a single page it is getting called 5 to 6 times. Is there any way I can reduce those calls, like store data in some variable and return the same if it is not empty.

Would appreciate any help.

Here is the function:

public function getResponse($connection)
{
    $query="select * from test order by date DSC";
    $arr = $connection ->query($query); //fetch all the data from query                   
    return $arr;
}

Upvotes: 0

Views: 60

Answers (2)

John Green
John Green

Reputation: 13435

It sounds like you want something like this.

HOWEVER, you should't cache the response, you should capture the data (rows) out of the response. Otherwise, you'll have pointer issues and other problems. Instead, do whatever data conversion you want to do on the resultant rows, and store them in a similar manner.

private $_response_cache = null;
public function getResponse($connection)
{
    if (is_null($this->_response_cache))
    {
        $query="select * from test order by date DSC";
        $this->_response_cache = $connection ->query($query); //fetch all the data from query                   
    }
    return $this->_response_cache;
}

If you need it statically, here... but even more warnings. Static code is problematic outside of constructors and should be used with caution. It screws with unit testing and can cause weird side effects -- there is a large school that suggests never using it, and although I don't subscribe to that school, I do recognize that improper usage is easy and dangerous.

private static $_response_cache = null;
public function getResponse($connection)
{
    if (is_null(self::$_response_cache))
    {
        $query="select * from test order by date DSC";
        self::$_response_cache = $connection ->query($query); //fetch all the data from query                   
    }
    return self::$_response_cache;
}

Upvotes: 2

flauntster
flauntster

Reputation: 2016

As mentioned, you've already answered the question, but if you're new to PHP then you use code such as:

// define variable
$response = null;

// then everywhere you're currently calling it, you could use:
$response = ($response == null) ? getResponse($conn) : $response;

Basically this checks if the variable is already holding the value returned from the function (ie has it been called already) and if so, uses that value otherwise calls the function and stores the returned value in the variable $response.

Hope this helps :)

Upvotes: 2

Related Questions