Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO Caching

Tags:

php

caching

pdo

I've been looking for an answer to this but haven't found it anywhere. Are calls to PDO::prepare() cached, or should I cache the result myself, i.e. if I do the following

function foo () {
  $handle = PDO::prepare(...);
  /* do stuff with the handle */
}

will the prepare() statement be cached by PDO so that it's quickly retrieved the second, third etc. times? Or is it better to do it myself, e.g.

function foo() {
  static $handle = null;
  if (!$handle) {
    $handle = PDO::prepare(...);
  }
  /* do stuff with the handle */
}
like image 360
El Yobo Avatar asked Dec 10 '09 22:12

El Yobo


People also ask

How does PHP store data in cache?

than we declare a variable of $cache_file and check that the file is exist or not. so in the very first time this is not exist so we fetch all records from database and store in our $cache_file by using predefined file functions.

What is PHP cache?

A cache is a collection of duplicate data, where the original data is expensive to fetch or compute (usually in terms of access time) relative to the cache. In PHP, caching is used to minimize page generation time.

What is query cache in MySQL?

The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again.


2 Answers

There is the MySQL query cache. But in general you should definitely keep the identifier for the prepared statement and re-use it.

The query cache is gone in MySQL version 8.0, see

https://dba.stackexchange.com/questions/217577/why-mysql-remove-query-cache-in-8-0-version

https://mysqlserverteam.com/mysql-8-0-retiring-support-for-the-query-cache/

like image 143
VolkerK Avatar answered Sep 22 '22 05:09

VolkerK


Two subsequent calls to PDO::prepare() (even with the same SQL query) should return two different PDOStatement (or handles) to avoid collisions, especially between previous and current bindings you may apply to it. The cost of creating a PDOStatement with prepare() is low anyway. What you may want cached are the results returned from the same SQL query, either raw or built by prepare() and this is a feature of your DBMS (MySQL for instance), not PHP.

like image 38
Percutio Avatar answered Sep 22 '22 05:09

Percutio