Query Caching Using query($sql) Breaks getNumRows()

I am using Cakephp 1.1.11.4064 and a Postgresql database. I was having trouble in my application where the value returned from getNumRows() was incorrect in certain places.

The problem turned out to be Cake’s query caching. Example code

$sql_1 = “sql statement 1;”;
$parent_result_1 = $this->query($sql_1);
.
.
.
Lots of code here
.
.

$sql_2 = “sql statement 2;”;
$parent_result_2 = $this->query($sql_2);
$num_rows_2 = $this->getNumRows();

$sql_1 = “sql statement 1;”;
$parent_result_1 = $this->query($sql_1);
$num_rows_1 = $this->getNumRows();

During the execution of the application, the query for $sql_1 is put in the cache. Later on, the query for $sql_2 executes. Then when the query for $sql_1 in encountered again, the query is not executed, but the results are pulled from the cache. Unfortunately, however, the getNumRows function returns the number of rows from the previous database query, which happens to be the query for $sql_2. Thus, $num_rows_1 ends up being the same as $num_rows_2, which breaks my application.

The solution I found is to disable query caching for any query that will be followed by a getNumRows command, as follows:

$sql_1 = ” sql statement 1;”;
$parent_result_1 = $this->query($sql_1, ‘false’);
$num_rows_1 = $this->getNumRows();


Share this post:

Facebooktwittergoogle_pluspinterestlinkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.