Caching PDO prepared statements

旧街凉风 提交于 2020-01-05 08:56:54

问题


Is there any point in saving PDO prepared statements for reuse in a session?

I'm building a site that uses MySQL fulltext queries, which I'm putting together in my PHP, like

SELECT * FROM table 
WHERE MATCH (title) AGAINST ($search_string IN BOOLEAN MODE) AND 
      MATCH (keywords) AGAINST ($keywords IN BOOLEAN MODE)
ORDER BY $order_by $asc_desc

It seems to take a lot longer to run this kind of query when I prepare and execute it with bound parameters, than when I just prepare and execute a query string with the values included. But I need to use prepared statements to prevent the risk of SQL injection.

In any session I would very likely run the same query several times, with different parameter values. Would it make sense for me to save the PDOStatement object once it's been created (for example in the session)? If so, what would be the best way to do that? Would it be good practice to save each prepared statement in an associative array as it's created, with the SQL query string as the key for each?


On further reading I found you can't use bound params for the ORDER BY and ASC / DESC part of a statement. When I replace these with fixed values the performance improves.


回答1:


There is no benefits to store prepare statement into session for reusable purpose,
the expensive cost is on the query execution itself.




回答2:


If the data you are grabbing constantly changes, then caching the resultset may no longer be valid shortly after you retrieve them.

However, if your data appears to be static:

session_start();
$_SESSION['cachedResultSet'] = $fetchedResultset;
echo $_SESSION['cachedResultSet'][0][0]; 
# above statement `echo ...` depends on how your result is, be it an array or object

I think it would be acceptable to a degree to store resultsets in session variables, but perhaps it would depend (sorry to be redundant) whether the data changes quickly or on how often you grab this particular resultset, etc...



来源:https://stackoverflow.com/questions/8202391/caching-pdo-prepared-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!