dongyilu3143
dongyilu3143
2014-09-17 07:08
浏览 53
已采纳

你应该在PHP中缓存MySQL连接吗?

Are there any disadvantages to caching a MySQL connection?

For example,

$mysqli = new mysqli(params);
apc_store('mysqli', $mysqli);

This would save some time if there are lots of users on your site all requiring connections. Instead of opening a connection for every user, why not cache it?

I haven't found anything by googling, so just wondering if I've missed something.

Thanks for your time.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • ds34222
    ds34222 2014-09-17 07:14
    已采纳

    A mysqli object is not something you can cache. It's a resource, not a plain object.

    Fetching it out of the cache would require it to reconnect to the database server, which means that the cached version would need to store a password in plaintext, which makes it a security flaw if you could cache it.

    Also, there's no guarantee that the database server would still be available when you fetch it out of the cache.

    And there's no way for multiple PHP requests to share the same cached resource. There's all sorts of problems with this plan.

    What is a solution for your goal is persistent mysqli connections, so the PHP runtime environment maintains some number of connections and can reuse them from one PHP request to the next.

    点赞 评论

相关推荐