In my CMS, sometimes I will make redundant queries because everything is independent. Is it ok to cache queries like this?:
global $cache_query, $cache_result;
if(!is_array($cache_query) || !is_array($cache_result) || !in_array($q,$cache_query))
{//The query is new.
$r = query_($q);
$cache_query[] = $q;
$cache_result[] = $r;
}
else
{//The query is cached.
foreach($cache_query as $k=>$c) // Cycle through my cached queries to find the key. Is there an getElementKey function?
if($c == $q) {
if(@mysql_fetch_array($cache_result[$k])) // is the resource is still valid?
mysql_data_seek($cache_result[$k], 0); // rewind the pointer
else
$cache_result[$k] = query_($q); // reset the resource
$r = $cache_result[$k];
break;
}
}
return $r;
OR is a better practice to just make a new query each time?
$q is my query, and the function query_() returns a resource and logs if something goes wrong.
Database queries are frequently a huge portion of your execution time, so if you can cache them you should.
That said, it might be better to save them off in named variables (or named variables in an associative array). Why are you walking through the array instead of just doing: