Search code examples
phpmysqlpdopersistent

Persistent connection: MySQL FOUND_ROWS() results


As a word of background, in MySQL, with the SQL_CALC_FOUND_ROWS flag and the FOUND_ROWS() function, MySQL lets you retrieve the total number of rows that would be returned if a SELECT did not use a LIMIT, without the need to issue a second heavy query:

$query =  "SELECT SQL_CALC_FOUND_ROWS * from movies
            WHERE....
            LIMIT 20";
$res1 = $db->query($query);
$numrows = $db->query('SELECT FOUND_ROWS()')->fetchColumn();

This can be useful for pagination. Suppose you are using a persistent connection:

try{
  $db = new PDO('mysql:host=localhost;dbname=' . $dbname, $user, $pass,
        array( PDO::ATTR_PERSISTENT => true )
               );
etc.

If two users click nearly simultaneously, is there any way that the requests could cross paths and one could get data requested by the other?


Solution

  • No, this is not a problem.

    As far as your PHP page is concerned, it has its own, unique connection for the duration of the page. The only difference with a Persistent connection from a Non-persistent connection is that after the page has exited, the connection isn't torn down, but put back into a pool for handing to some other page. In other words, it's not a shared connection, it's a reused connection. If there are 35 pages all serving a page request at the same time, there will still be 35 simultaneous connections to your database.

    You have to be careful of propagating connection state (such as incomplete transactions), though, but that's a separate problem.