Tuesday 11 December 2012

SQL_CALC_FOUND_ROWS / FOUND_ROWS() does not work in PHP

$s1 = $sql->query('select SQL_CALC_FOUND_ROWS * from db limit 0, 3');
$s2 = $sql->query('select FOUND_ROWS()');
if($row = $s2->fetch_row()) printf('%d/%d', $s1->num_rows, $row[0]);
Sometime, when we run something analogous to above example on the mysql command line, it would work; but running it from php, it failed. The second query has to "know about" the first one, so for some reason its persistence/memory linking the two queries was getting messed up by the php.

(It turns out that Wordpress uses this type of query to do its pagination - so our larger problem was that the pagination in a wordpress install suddenly stopped working when we moved to php 5.2.6 ... eventually tracked it down to the FOUND_ROWS()).

Just for the sake of posting for people who may run into this in the future... for me it was the php setting "mysql.trace_mode" - this defaulted "on" in 5.2.6 instead of "off" like previously, and for some reason prevents the FOUND_ROWS() from working.

As a "fix", we could either put this in every php page (actually, in a common "include"):
ini_set("mysql.trace_mode", "0");
or add this to the .htaccess:
php_value mysql.trace_mode "0"