有没有办法在PHP中保持与mysql数据库的连接?

Im trying to optimize some of my PHP code. I found out that most time of my PHP script is spent during the connection to my mysql database at the beginning of the script.

I only connect to the database once at the beginning and close the database connection at the end of the script.

But for each user requesting this page a new connection has to be established.

Is there a way to hold a reference to the database and share it for all requests?

You can make your connection persistent (for PDO use PDO::ATTR_PERSISTENT => true), but my recomandation is to find out why your script is spending a lot of time connecting to mysql and make some improvments there.

Consider this:

  • Use MySQL server IP instead of hostname, to eliminate time needed to resolve dns.
  • Disable mysql autocompletition: (comment skip-auto-rehash from my.cnf)
  • If you make a lot of queries which will return the same thing over and over again, consider using a caching system to cache for query results.
  • Post your code on codereview.stackexchange.com to benefit from others expertise on further improving your code.
  • To further debug the problem, connect from console to MySQL server and check the time needed to open connection, change database, select, etc.

Yes, you can achieve that.

If you're using the MySQLi extension (the old one without the i at the end is outdated!), you can create a persistent connection by passing p: as a prefix to the hostname when creating the instance:

See mysqli::__construct.

If you're really using the old MySQL extension, there's mysql_pconnect for persistent connections.


Alternatively, if you're using PDO, then you can use setAttribute() to use PDO::ATTR_PERSISTENT.

Documentation on using persistent connection in PDO.