I have a script that is taking too long to run and I have been working on optimizing it to be quicker. One thing I know is taking extra time is the fact that i have to run the same query multiple times. I’d like to be able to store the result of that query (without writing it to a db) so that I can reference it’s value later without having to run the query again.
I am dramatically simplifying the script below but hopefully this gives you an idea.
Let’s say i have two functions that each return a value:
function a(){
$query = "SELECT SUM(price) FROM table_1 WHERE zip='$this->zip'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
return $row['SUM(price)'];
}
function b(){
$query = "SELECT SUM(price) FROM table_2 WHERE zip='$this->zip'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
return $row['SUM(price)'];
}
Let’s suppose function a() returns a value of 10 and function b() returns a value of 5
Now, suppose my script is something like this:
if (function a() > 5) { echo 'it is greater than 5!' }
if (function a() < 5) { echo 'it is less than 5!' }
if (function b() == 5) { echo 'it equals 5!' }
if (function b() > 10) { echo 'it is not greater than 5!' }
If i understand things properly, the script above causes 4 separate queries of my database. It is possible to store the initial running of each query? One thing i thought of was doing this:
$a = function a();
$b = function b();
And then having my script like this:
if ($a > 5) { echo 'it is greater than 5!' }
if ($a < 5) { echo 'it is less than 5!' }
if ($b == 5) { echo 'it equals 5!' }
if ($b > 10) { echo 'it is not greater than 5!' }
Will that cause the queries to only run once each at the point when i define $a and $b? Is there another method to consider that i am not thinking of?
Thanks for your help!
Yes, this will cause your queries to only run once. If you want to ensure that they run once per session without manually caching the result in a variable every time, you could look into an ORM with some caching ability, or use static variables inside each function:
If you don’t want to use an ORM, you should at the very least be writing your own slim series of wrapper functions around database access, rather than manually calling
mysql_queryin every function. There should really be only one point where your app touches the database through themysql_*family of functions. This isolates change; had you implemented a small wrapper around your database access in the first place, you would now only have one place to change in order to ditch the datedmysql_queryfunctions in favour of PDO.